I can't really visualise what's going on in this code. We're simply
reading splitting each line of a file and saving the result in a
hash, right?
How can I print the contents of the hash?
As you will no doubt learn very rapidly if you read this group, you
ought to start every Perl program with the incantation:
use strict;
use warnings;
which allows Perl to help you by spitting out lots of useful information
about possible mistakes in your program.
open(FILE, 'orig.txt') or die "Can't open orig.txt: $!";
my @fields = qw/a b c d e f g h i j k/;
my $record = <FILE>;
<> in scalar context returns a single line from a file, so this will
read the first line of the contents of FILE into $record. It's not
really necessary in this instance (see below).
Whereas <> as the sole condition for a while loop is magic, and is
shorthand for:
while ( $_ = <FILE> ) {
So in this case I suspect you would be better off with the condition
while ( my $record = <FILE> ) {
This will work the first time around the loop, but in your original
program you're not updating the value of $record anywhere, making it a
fairly worthless statement.
You are using my() within a block (the {..} construct of the while
loop). This will lexically scope the variable to a *single iteration* of
the loop. In other words, you are creating a new %hash variable every
time you read another line from FILE. And losing it almost immediately.
Do you really want a new hash for each line of the file, or are you
trying to aggregate the data in some form?
@hash{@fields} = split(/\t/, $record);
You are trying to assign to a hash slice of exactly 11 keys. Is this
what you want -- in other words, can you guarantee that each line of
FILE contains 11 items each separated by a single tab character?
}
print "$. records processed.\n";
This works, but it's probably clearer to use an explicit line-counter
variable. That will also have the advantage that it won't get reset if
you close() the file.
And I haven't yet touched upon how you might view the contents of your
hash, but see the following. Note that it probably isn't doing what you
expect or want (unles you really DO want the hash to be overwritten on
each iteration), but it should give you a clearer idea of what's going
on.
#!perl
use strict;
use warnings;
open(FILE, 'orig.txt') or die "Can't open orig.txt: $!";
my @fields = qw/a b c d e f g h i j k/;
my $lines = 0;
while (my $record =<FILE>) {
chomp $record;
my %hash;
@hash{@fields} = split(/\t/, $record);
$lines++;
print "After $lines lines, hash contains:\n";
# A simple way to print the contents of a hash:
foreach ( sort keys %hash ) {
print " $_ => $hash{$_}\n";
}
}
close FILE;
print "$lines records processed.\n";