开发者

Writing to a file in perl

I want to write the key and value pair that i have populated in the hash.I am using

open(OUTFILE,">>output_file.txt");
{
    foreach my $name(keys %HoH) {
        my $values = $HoH{$name}开发者_Python百科;
        print "$name: $values\n";
    }
}
close(OUTFILE); 

Somehow it creates the output_file.txt but it does not write the data to it.What could be the reason?


Use:

 print OUTFILE "$name: $values\n";

Without specifying the filehandle in the print statement, you are printing to STDOUT, which is by default the console.


open my $outfile, '>>', "output_file.txt";

print $outfile map { "$_: $HOH{$_}\n" } keys %HoH;

close($outfile);

I cleaned up for code, using the map function here would be more concise. Also I used my variables for the file handles, always good practice. There are still more ways to do this, you should check out Perl Cook book, here


When you open OUTFILE you have a couple of choices for how to write to it. One, you can specify the filehandle in your print statements, or two, you can select the filehandle and then print normally (without specifying a filehandle). You're doing neither. I'll demonstrate:

use strict;
use warnings;
use autodie;

my $filename = 'somefile.txt';

open my( $filehandle ), '>>', $filename;
foreach my $name ( keys %HoH ) {
    print $filehandle "$name: $HoH{$name}\n";
}
close $filehandle;

If you were to use select, you could do it this way:

use strict;
use warnings;
use autodie;

my $filename = 'somefile.txt';

open my( $filehandle ), '>>', $filename;
my $oldout = select $filehandle;
foreach my $name( keys %HoH ) {
    print "$name: $HoH{$name}\n";
}
close $filehandle;
select $oldout;

Each method has its uses, but more often than not, in the interest of writing clear and easy to read/maintain code, you use the first approach unless you have a real good reason.

Just remember, whenever you're printing to a file, specify the filehandle in your print statement.


sergio's answer of specifying the filehandle is the best one.

Nonetheless there is another way: use select to change the default output filehandle. And in another alternate way to do things, using while ( each ) rather than foreach ( keys ) can be better in some cases (particularly, when the hash is tied to a file somehow and it would take a lot of memory to get all the keys at once).

open(OUTFILE,">>output_file.txt");
select OUTFILE;
while (my ($name, $value) = each %HoH) {
    print "$name: $value\n";
}
close(OUTFILE);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜