A
A. Sinan Unur
As has been mentioned somewhere above, that's simply incorrect code in
most circumstances. while (<handle>) { ... } is a special case and if
you really must use a named variable the construct should be
while (defined(my $var = <>)) { ... }
As far as I know, the magic test for defined in a while loop is the same
whether you are reading into a $_ or any lexical variable. Here is a
short test:
C:\DOCUME~1\asu1\LOCALS~1\Temp\m> cat m.txt
0
1
2
3
4
C:\DOCUME~1\asu1\LOCALS~1\Temp\m> xxd m.txt
0000000: 300a 310a 0a32 0a33 0a0a 340a 0a 0.1..2.3..4..
C:\DOCUME~1\asu1\LOCALS~1\Temp\m> cat m.pl
#!/usr/bin/perl
use strict;
use warnings;
my $name = 'm.txt';
my %dispatch = (
without_defined => \&without_defined,
with_defined => \&with_defined,
without_var => \&without_var,
);
for my $case ( sort keys %dispatch ) {
print "$case:\n";
open my $f, '<', $name
or die "Cannot open '$name': $!";
$dispatch{ $case }->( $f );
close $f
or die "Cannot close '$name': $!";
}
sub without_defined {
my $f = shift;
while ( my $line = <$f> ) {
print decorate($line);
}
}
sub with_defined {
my $f = shift;
while ( defined( my $line = <$f> ) ) {
print decorate($line);
}
}
sub without_var {
my $f = shift;
while ( <$f> ) {
print decorate($_);
}
}
sub decorate {
my ($s) = @_;
$s =~ s/\n/</;
return "'$s'\n";
}
__END__
C:\DOCUME~1\asu1\LOCALS~1\Temp\m> m
Without var assignment in while:
'0<'
'1<'
'<'
'2<'
'3<'
'<'
'4<'
'<'
With 'defined' in while:
'0<'
'1<'
'<'
'2<'
'3<'
'<'
'4<'
'<'
Without 'defined' in while:
'0<'
'1<'
'<'
'2<'
'3<'
'<'
'4<'
'<'