Mailing List Archive

Simple print question..
Hi,
I am VERY new to perl and I'm not sure if this is the correct place to send
duncy type questions ( if not where ) but here goes..

Why does the print not work in example 1 but work in 2

1)
FILE:
while( $filename = <LISTOFFILES> )
{
$filename =~ /\.c$/ && print $filename && next FILE;
}

2)
FILE:
while( $filename = <LISTOFFILES> )
{
if( $filename =~ /\.c$/ )
{
print $filename;
next FILE;
}
}

The reason for the next is because there is more to the while statement
which I won't want to do if the condition is met.

Thanks
Simon....

NB: Running on an RS6000 ( AIX V3.2.5 )
Re: Simple print question.. [ In reply to ]
>I am VERY new to perl and I'm not sure if this is the correct place to send
>duncy type questions ( if not where ) but here goes..

Well, comp.lang.perl.misc would be better.

>Why does the print not work in example 1 but work in 2

>1)
>FILE:
>while( $filename = <LISTOFFILES> )
>{
> $filename =~ /\.c$/ && print $filename && next FILE;
>}


Due to precendence. You wrote

($filename =~ /\.c$/) && (print($filename && next FILE));

which isn't going to be what you want, since the next FILE
gets eval'd before the print can be called. whoops.

(i always kinda wondered why larry made and next/last/redo
TERMs (sans retvals))

As you discovered, the best way is the clear way:

FLIST: while ( $filename = <LISTOFFILES> ) {
chomp $filename;
if ($filename =~ /\.c$/) {
print $filename, "\n";
next FLIST;
}
}

Or even

while ( <LISTOFFILES> ) {
if (/\.c$/) { print; next; }
chomp;
}

but I'm a little leary of

while ( <LISTOFFILES> ) {
do { print; next; } if /\.c$/;
chomp;
}

and even more so of comma abuse

while ( <LISTOFFILES> ) {
print, next if /\.c$/;
chomp;
}

Actually, you get into trouble with do. Imagine

do { warn "hiya" } if 0;

Does that print? Nope.

do { warn "hiya" } while 0;

Why yes, it does. That's cuz do{}while/until EXPR evals
the EXPR after the do, but the others do before. (i thought
they all used to before, but i gues not).

--tom