IPstacks has asked for the wisdom of the Perl Monks concerning the following question:

I would like to open a file and grep each line for "--foo" and have it print everything else on the line except for the --foo then have it repeat until it reaches the end of the file.

I assume I'll have to have something similar to this:
open FILE, $filename or die "Can't open file: $!/n"; while (<FILE>) { $data = <FILE>; $foo = grep $data ("--from"); print $foo; } close FILE;
But I'm not sure how I can get it to only print text that is after my search string.
Thanks again for your help!

Replies are listed 'Best First'.
Re: Array Search
by rob_au (Abbot) on Nov 14, 2001 at 07:28 UTC
    Solution using the postmatch variable $' ...

    open FH, $filename || die $!; foreach (<FH>) { next unless $_ =~ /--from/; print $'; }; close FH;

    Update - Removed the conditional 'untested' from the term solution

     

    Ooohhh, Rob no beer function well without!

      Either

      open FH, $filename or die $!;

      or

      open (FH, $filename) || die $!;

      but with your variant you'll never see the error message (operator precedence).

      Sorry to be nitpicking, but I stumbled over that one myself once...

      pike

Re: Array Search
by lestrrat (Deacon) on Nov 14, 2001 at 07:37 UTC

    You're confusing grep() with UNIX's grep utility. check out perldoc -f grep, and you will see. You're also slurping <FILE>...

    Here's another way to do it...

    while( <FILE> ) { if( my $pos = index( $_, '--foo' ) ) { $pos += 5; print substr( $_, $pos, length($_) - $pos ); } }
      A quick thing here ... if you omit the third parameter from substr, the length parameter, it will return everything up to the end of the line already for you. eg.

      print substr($_, $pos);

      See perlfunc:substr

       

      Ooohhh, Rob no beer function well without!

Re: Array Search
by pike (Monk) on Nov 14, 2001 at 14:57 UTC
    Actually, using grep here is OK, you just have to adjust the syntax:

    open FILE, $filename or die "Can't open file: $!\n"; my @recs = grep {s/^.*--from//} <FILE>; print @recs; close FILE;

    pike