Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I skip to a specific input line in Perl?

Tags:

loops

perl

I want to skip to the first line that contains "include".

<> until /include/;

Why does this not work?

like image 597
user44511 Avatar asked Dec 11 '08 17:12

user44511


2 Answers

The match operator defaults to using $_ but the <> operator doesn't store into $_ by default unless it is used in a while loop so nothing is being stored in $_.

From perldoc perlop:

   I/O Operators
   ...

   Ordinarily you must assign the returned value to a variable, but there
   is one situation where an automatic assignment happens.  If and only if
   the input symbol is the only thing inside the conditional of a "while"
   statement (even if disguised as a "for(;;)" loop), the value is auto‐
   matically assigned to the global variable $_, destroying whatever was
   there previously.  (This may seem like an odd thing to you, but you’ll
   use the construct in almost every Perl script you write.)  The $_ vari‐
   able is not implicitly localized.  You’ll have to put a "local $_;"
   before the loop if you want that to happen.

   The following lines are equivalent:

       while (defined($_ = )) { print; }
       while ($_ = ) { print; }
       while () { print; }
       for (;;) { print; }
       print while defined($_ = );
       print while ($_ = );
       print while ;

   This also behaves similarly, but avoids $_ :

       while (my $line = ) { print $line }
like image 199
Robert Gamble Avatar answered Sep 28 '22 01:09

Robert Gamble


<> is only magic in a while(<>) construct. Otherwise it does not assign to $_, so the /include/ regular expression has nothing to match against. If you ran this with -w Perl would tell you:

Use of uninitialized value in pattern match (m//) at ....

You can fix this with:

$_ = <> until /include/;

To avoid the warning:

while(<>)
{
    last if /include/;
}
like image 30
Hudson Avatar answered Sep 28 '22 00:09

Hudson