Single questions about file processing in perl

D

dima

Hello all!

The following code is correct :

open(FD,"< my.txt") or die("Error");
while(<FD>)
{
print "$_\n";
exit(0) if ($_eq "STOP");
}

But this code work incorrect :

open(FD,"< my.txt") or die("Error");
$_="NOT_STOP";
while(<FD> and ($_ne "STOP") )
{
print "$_\n";
}
print "$_\n";
exit(0);
Both example are equivalent? Or I wrong?

Furthermore, why this code is incorrect :
while(<FD> and 1)
{
print "$_\n";
}
Thanks!
 
P

Paul Lalli

Hello all!

The following code is correct :

open(FD,"< my.txt") or die("Error");
while(<FD>)
{
print "$_\n";
exit(0) if ($_eq "STOP");
}

But this code work incorrect :

This is a poor error description. You should always tell us HOW it is
incorrect. What did it not do that you expected it to do?
Fortunately, in this case, the answer is plain.
open(FD,"< my.txt") or die("Error");
$_="NOT_STOP";
while(<FD> and ($_ne "STOP") )
{
print "$_\n";
}
print "$_\n";
exit(0);
Both example are equivalent? Or I wrong?

Unfortunately, they are not equivalent. The construct of
while (<FD>){ ... }
is "magical". When <> is the only operation or statement inside the
while() condition, then, AND ONLY THEN, does $_ get assigned the return
value of the <> operation. In ANY other circumstance, you need to
explicitly assign $_.

while (defined($_ = said:
Furthermore, why this code is incorrect :
while(<FD> and 1)
{
print "$_\n";
}

Same reason as above. The auto-assigning of $_ = <FD> occurs if and
only if <FD> is the ONLY thing inside the while() condition. putting
the additional code ("and 1") in the parentheses prevents this magic.

Hope this helps,
Paul Lalli
 
J

Joe Smith

The following code is correct :

open(FD,"< my.txt") or die("Error");
while(<FD>)
{
print "$_\n";
exit(0) if ($_eq "STOP");
}

No, that is not correct. Since you neglected to chomp(), it prints
out the contents of the file double spaced and does not stop at a
line with "STOP" (unless you have a premature end-of-file).
-Joe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top