On Aug 7, 5:06 pm, [EMAIL PROTECTED] (Rob Dixon) wrote:
> Anees wrote:
> > Dear friends:
>
> > I am a perl begineer. I have created an script which prints each 100th
> > record from the file as shown below:
>
> > #!/usr/bin/perl
> > $maxRecords=20000;
> > $steps=100;
>
> > $index=1;
> > $recCounter=0;
> > while (<>){
> >     if(defined) {
> >         if (($index % $steps) == 0) {
> >             print $_;
> >             $recCounter++;
> >         }
> >         if($recCounter > $maxRecords){ break; }
> >         $index++;
> >     }
> > }
>
> > The above script works fine. But when I modify the script as follows:
>
> > #!/usr/bin/perl
> > $maxRecords=20000;
> > $steps=100;
>
> > $index=1;
> > $recCounter=0;
> > while (<> && defined){
> >         if (($index % $steps) == 0) {
> >             print $_;
> >             $recCounter++;
> >         }
> >         if($recCounter > $maxRecords){ break; }
> >         $index++;
> > }
>
> > I won't give me any records.
> > Can you please identify the difference in behavior ?
>
> The special behaviour of while .. readline (assigning the record to $_ and 
> then
> checking for definedness) only happens when the while condition contains just 
> a
> single <> operator. If you make it more complicated than that then perl 
> compiles
> exactly what you write, so
>
>   while (<>) { .. }
>
> reads a record from the file, assigns it to $_, exits the loop if $_ is
> undefined, and then executes the body of the loop. It is the same as
>
>   while (defined($_ = <>)) { .. }
>
> whereas
>
>   while (<> && defined) { .. }
>
> reads a record from the file, discards it, exits the loop if $_ is undefined,
> and then executes the body of the loop, which is what you asked for :)
>
> HTH,
>
> Rob

Thank you all. I got the idea. defined not needed, and $_ is assigned
only in simplest form. Thanks again. :)


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to