open FH, '<', 'myfile';
print FH, "something\n";
####
No comma allowed after filehandle at ...
##
##
open my $fh, '<', 'myfile';
print $fh, "something\n";
##
##
open local *FH, '<', 'myfile';
while () {
# do something
}
close FH;
##
##
#!/usr/bin/perl
use Test2::V0;
package Foobar;
our $foobar = "foobar\n";
our @foobar;
sub use_fh {
# unlocalized use of FH in separate package
open FH, '<', \$foobar;
@foobar = ;
close FH;
}
package main;
my $foo = "foo\n";
my $bar = "bar\n";
my $baz = "baz\n";
my @baz;
sub use_localized_fh {
# protect caller's FH
open local *FH, '<', \$baz;
@baz = ;
close FH;
}
sub close_fh {
# unlocalized use of FH
close FH;
}
# open now, use later
open FH, '<', \$bar;
my @foo;
# create new scope
{
# use localized FH, protecting handle opened on \$bar
open local *FH, '<', \$foo;
# call sub that uses localized FH
use_localized_fh;
# call sub in other package that uses FH
Foobar::use_fh;
# FH still intact
@foo = ;
close FH;
}
is \@baz, [$baz], 'got $baz in sub';
is \@Foobar::foobar, [$Foobar::foobar], 'got $Foobar::foobar in foreign sub';
is \@foo, [$foo], 'good: got $foo';
{
open local *FH, '<', \$foo;
# call sub that closes FH
close_fh;
@foo = ;
close FH;
}
is \@foo, [], 'bad: FH was closed in sub';
# FH at this scope is still untouched
my @bar = ;
close FH;
is \@bar, [$bar], 'good: got $bar';
done_testing;