ハッシュのリファレンスに持ったファイルハンドルを処理するとき

そういうときは<>演算子じゃなくて、readlineだよってお話。

#!/usr/bin/perl
use strict;
use warnings;

our $test = './test.txt';

my $hashref = fh_open($test);
while(<$hashref->{handle}>){
        print;
}
exit();

sub fh_open{
        my $filename = shift;
        open my $handle, '<', $filename or die $!;
        return { file => $filename, handle => $handle };
}

実行結果

syntax error at ./handle.pl line 8, near "<$hashref->{handle"
Execution of ./handle.pl aborted due to compilation errors.
#!/usr/bin/perl
use strict;
use warnings;

our $test = './test.txt';

my $hashref = fh_open($test);
while(readline($hashref->{handle})){
        print;
}
exit();

sub fh_open{
        my $filename = shift;
        open my $handle, '<', $filename or die $!;
        return { file => $filename, handle => $handle };
}

実行結果

I am Test File
haha