http://qs1969.pair.com?node_id=495845

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

I have multiple line file and I am trying to extract only START .. END part it works one way but not another ?.
#Input file: #SomeChar # START #value # END #AnotherChar #This code extract START .. END (OK) while (<>) { my $stag='START'; my $etag='END'; my $line; $line=$_; if ($line=~/$stag/../$etag/) { print $line; } } #This code extract START .. END + everything after (NOT GOOD) sub getInfoFromMultipleLine { #Openning file for reading open(IFH,"$InputFile") || die "Can't open file: $InputFile\n"; my $stag='START'; my $etag='END'; my $line; while($line=<IFH>) { if ($line=~m/$stag/../$etag/) { print $line; } } } $InputFile="$LocationOfTheScriptsDirectory\\A.txt"; getInfoFromMultipleLine();
Thanks in advance Gasho

Replies are listed 'Best First'.
Re: How to extract Start .. End from multiline file
by halley (Prior) on Sep 28, 2005 at 17:56 UTC
    Two things of note. The two lines of code below are identical, thanks to magic in the perl parser.
    while (<fh>) { ... } while (defined ($_ = <fh>)) { ... }
    Your code, shown below, does not work the same way. {update: proven wrong below, but I still wouldn't use it}
    while ($var = <fh>) { ... }
    Also, the .. operator can't be used in the way you're working on your latter example. It needs to go between two complete expressions that will be evaluated for the range flipflop. You wrote:
    if ($line =~ m/$stag/ .. /$etag/)
    You meant:
    if (($line =~ m/$stag/) .. ($line =~ m/$etag/))
    Perl thought you meant:
    if (($line =~ m/$stag/) .. ($_ =~ m/$etag/))
    See it? You never assigned to $_ so it never got the end condition.

    --
    [ e d @ h a l l e y . c c ]

      Your code, shown below, does not work the same way.

      This is a common myth. I (pretty recently) used to believe the same thing. Deparse shows us the light, though:

      $ perl -MO=Deparse -e 'while ($var = <fh>) {}' while (defined($var = <fh>)) { (); }
      Your code, shown below, does not work the same way.

      Are you sure?

      >perl -MO=Deparse -e "while ($var = <fh>) { }" while (defined($var = <fh>)) { (); } -e syntax OK
      Thanks Ed for quick response Line:
      if (($line =~ m/$stag/) .. ($line =~ m/$etag/))
      did work fine :)
Re: How to extract Start .. End from multiline file
by borisz (Canon) on Sep 28, 2005 at 17:55 UTC
    while(<>){ next unless /START/ .. /END/; print }
    Boris
Re: How to extract Start .. End from multiline file
by svenXY (Deacon) on Sep 28, 2005 at 18:04 UTC
    Hi,
    but it works like that (it's a bit more like the OP code):
    sub getInfoFromMultipleLine { #Openning file for reading open(IFH,"$InputFile") || die "Can't open file: $InputFile\n"; my $stag='START'; my $etag='END'; my $line; while(<IFH>) { print if /$stag/../$etag/; } }

    Regards,
    svenXY