khurana.sanjeev has asked for the wisdom of the Perl Monks concerning the following question:

I have a file content like this 111 222 333 444 555 222 777 888 I want to search the string 222 and then print the lines following the search in the file, but want to search through perl API, instead of iterating through the whole file.
  • Comment on Search a string through IO::File API, and then print the lines after match in the file.

Replies are listed 'Best First'.
Re: Search a string through IO::File API, and then print the lines after match in the file.
by Fletch (Bishop) on Sep 11, 2008 at 13:33 UTC

    Do you expect IO::File to provide some sort of magic pixies that just know a priori where your search term is in the file? Unless you have some sort of external index the only way to read through a file and find a matching line is to, well, read through the file looking for the matching line.

    Now if this is something you need to do repeatedly then you do want to look into building an index (there's an example in the Perl Cookbook, and I'm sure someone can chime in with supersearch fodder to turn up examples here; tell, seek, and some form of persistent hash are the key ingredients), or depending on the exact nature of your real problem maybe look at some sort of RDBMS capable of keeping an index for you.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: Search a string through IO::File API, and then print the lines after match in the file.
by ikegami (Patriarch) on Sep 11, 2008 at 20:54 UTC

    I don't see the point, but here goes anyway.

    Without IO::File interfaceUsing IO::File interface
    my $found; while (<$fh>) { if (/^222$/) { $found = 1; $last; } } print while <$fh>;
    local *_; my $found; while (defined($_ = $fh->getline())) { if (/^222$/) { $found = 1; $last; } } print while defined($_ = $fh->getline());

      Thanks a lot for reply. I feel perl API's would be using better searching methods then just searching the file from top to end. If they are not using, I agree my query doesn't make sense.
Re: Search a string through IO::File API, and then print the lines after match in the file.
by psini (Deacon) on Sep 11, 2008 at 13:25 UTC

    Why? Seems to me like an XY problem.

    Rule One: "Do not act incautiously when confronting a little bald wrinkly smiling man."