Front page | perl.perl5.porters |
Postings from May 2008
Confused about close STDIN
Thread Next
From:
Bram
Date:
May 25, 2008 15:21
Subject:
Confused about close STDIN
Message ID:
20080526001952.hr95ixllog0gc0cs@horde.wizbit.be
Looking at and old bug report and getting a bit confused about the
behaviour after closing STDIN...
First one:
#!/usr/bin/perl -l
use strict;
use warnings;
close STDIN;
open my $foo, "<", $0;
print fileno($foo);
while (<STDIN>) {
chomp;
print "<STDIN>: $_";
}
while (<>) {
chomp;
print "<> ($ARGV): $_";
}
__END__
Output:
readline() on closed filehandle STDIN at c.pl line 11.
<> (-): #!/usr/bin/perl -l
<> (-):
<> (-): use strict;
...
perlop says:
'The null filehandle <> is special: it can be used to emulate the
behavior of sed and awk. Input from <> comes either from standard
input, or from each file listed on the command line. Here's how it
works: the first time <> is evaluated, the @ARGV array is checked, and
if it is empty, $ARGV[0] is set to "-", which when opened gives you
standard input.'
Which might be confusing... since it doesn't use STDIN but it uses fd
0 directly (which normally is STDIN).
Second: (reduced from a bug report)
#!/usr/bin/perl -l
use strict;
use warnings;
close STDIN;
require IPC::Open2;
IPC::Open2->import;
open2(my $child_out, my $child_in, 'cat');
print "fileno(\$child_out): " . fileno($child_out);
print "fileno(\$child_in): " . fileno($child_in);
print $child_in "abc def";
close $child_in;
while (<$child_out>) {
chomp;
print "<\$child_out>: $_";
}
__END__
Output:
fileno($child_out): 5
fileno($child_in): 4
(in this case there is no output
Without the close STDIN:
#!/usr/bin/perl -l
use strict;
use warnings;
require IPC::Open2;
IPC::Open2->import;
open2(my $child_out, my $child_in, 'cat');
print "fileno(\$child_out): " . fileno($child_out);
print "fileno(\$child_in): " . fileno($child_in);
print $child_in "abc def";
close $child_in;
while (<$child_out>) {
chomp;
print "<\$child_out>: $_";
}
__END__
Output:
fileno($child_out): 5
fileno($child_in): 4
<$child_out>: abc def
Third one: adding an open after the close
#!/usr/bin/perl -l
use strict;
use warnings;
close STDIN;
open my $foo, "<", $0;
require IPC::Open2;
IPC::Open2->import;
open2(my $child_out, my $child_in, 'cat');
print "fileno(\$child_out): " . fileno($child_out);
print "fileno(\$child_in): " . fileno($child_in);
print $child_in "abc def";
close $child_in;
while (<$child_out>) {
chomp;
print "<\$child_out>: $_";
}
__END__
Output (1):
fileno($child_out): 5
fileno($child_in): 4
Output (2):
fileno($child_out): 5
fileno($child_in): 4
<$child_out>: #!/usr/bin/perl -l
<$child_out>:
<$child_out>: use strict;
...
In this code the output changes between each run...
Sometimes I get output (1), sometimes output (2). (without changing
the code obviously)
Should this behaviour be better documented (for example in perldoc -f close)?
Or is this a bug?
Kind regards,
Bram
Thread Next
-
Confused about close STDIN
by Bram