>> I need to search a particular string in a set of files in a directory. The
>> string appears only in one of the files in the directory.
>>  I need to retrieve the file name and then access the line of that
>> particular file in which the string occurs.
>>
>> NOTE: The perl script also resides in the same directory.
>>
>> For Eg: I am in search of string $string = "PERL_BEGINNER";
>> i have a directory => /Users/ and the files in that directory are:
>>                              1. Beginners.h
>>                              2. Learners.h
>>                              3. Experts.h
>>                              4. etc....
>>
>> Among these files $string occurs only in one of the files. If we assume
>> that it occurs in "Beginners.h"
>>
>> then Beginners.h has to be opened and the $string has to be searched in
>> that file.

>
>I forgot to mention, First step is to Search for the file in which the
>string occurs
>
>Second step is to Open the file in which the string is present
>
>Third Step is to Get the file pointer to the line in which the string
>occurs.


Hello,

1) At first you can open a dir and obtain all the *.h files in it.
It can write:

opendir DIR,"." or die $!;
while(my $file = readdir DIR) {
    next if $file eq '.' or $file eq '..';
    next if $file !~ /\.h$/;
    if ( defined my $re = search_the_string_from_this_file($file) ) {
        handle_this_result();
        last;
    }
}
closedir DIR;

2) Second you need to open the files each by each and search that string you 
wanted.
It can be done in this subroutine:

sub search_the_string_from_this_file
{
    my $file = shift;
    my $string = 'foo';
    open FILE,$file or die $!;
    while(<FILE>) {
        return $. if /$string/;
    }
    close FILE;
}

Comments:
1) Not like C,you can't obtain file pointer in Perl.The 
search_the_string_from_this_file() subroutine would only return the file's line 
number (stored in $. variable) where the $string appear in.Is it enough?

2) Here I just use regex for the search matching,but it's maybe very 
limited.You should improve the search arithmetic by yourself.

3) Not tested.

--
Jeff Pang
EMAIL: [EMAIL PROTECTED]  AIM: jeffpang

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to