[Israel.pm] simple script question.

Offer Kaye offer.kaye at gmail.com
Sun Sep 26 04:58:58 PDT 2004


On Sun, 26 Sep 2004 12:55:25 +0200, Prager, Mark wrote:
> Hi -
> I am trying to get the following short script to work -
> 
> #!/usr/local/bin/perl
> 
> while (<STDIN>)
> {
>         chomp;
>         if (/PrintThis/) # if the line contains the word Template - prints out this line, and the next;
>         {
>                 print "$_\n";
>                 <STDIN>;
>                 print "$_\n";
>         }
> }
> 

Hi,
Gabor already gave a good answer (for reference, the fact that <> only
assigns to $_ inside the condition of a while loop can be found in
"perldoc perlvar", in the section which talks about $_). I'll just add
that you seem to be doing unneccessary work here, because you use
chomp, but then add a newline when you print "$_\n". Using Gabor's
answer, but with $line replaced with $_, this could be re-written as:

while (<>)
{
       if (/PrintThis/) # if the line contains the word Template -
prints out this line, and the next;
       {
               $_ .= <>; # get also the next line
               print;
       }
}

Note that I:
1. Changed "<STDIN>" to "<>"  - they are the same.
2. Used the ".=" operator, which can be found in "perldoc perlop".

-- 
Offer Kaye



More information about the Perl mailing list