Perl: load file into hash

I am trying to understand the logic behind hashes in Perl. The task is to load the file into a hash and assign values ​​to the keys that are created using this file.

The file contains the alphabet with each letter on a separate line:

a
b
c
d
e

      

etc. When using an array instead of a hash, the logic is simple: load the file into an array and then print each element with the corresponding number using some counter ($ counter ++).

But now my question is, how can I read the file in my hash, assign the auto-generated values ​​and sort it in this way, where the output is printed like this:

a:1
b:2
c:3

      

I tried to create an array first and then concatenate it to a hash using

%hash = @array

      

but that makes my hash not sortable.

+3


source to share


3 answers


There are several ways to approach this. The most straight forward would be to load the data into a hash while reading the file.

my %hash;
while(<>)
{
    chomp;
    $hash{$_} = $.;    #Use the line number as your autogenerated counter.
}

      

You can also do symar logic if you already have a populated array.



for (0..$#array)
{
    $hash{$array[$_]} = $_;
}

      

Although, if you're in this situation, map is a perlier way to do things.

%hash = map { $array[$_] => $_ } @array;

      

+4


source


Think of a hash as a set of (key, value) pairs where the keys must be unique. You want to read the file one line at a time and add a pair to the hash:

$record = <$file_handle>;
$hash{$record} = $counter++;

      

You can of course read the entire file in the array at once and then assign your hash. But the solution is not like this:

@records = <$file_handle>;
%hash = @records;

      

... how did you find out. If you think in pairs (key, value), you will see that the above is equivalent:



$hash{a} = 'b';
$hash{c} = 'd';
$hash{e} = 'f';
...

      

etc. You still need a loop explicit like this:

foreach my $rec (@records)
{
    $hash{$rec} = $counter++;
}

      

or implicit, similar to one of these:

%hash = map {$_ => $counter++} @records;
# or:
$hash{$_} = $counter++  for @records;

      

+2


source


This code should generate correct output, where my-text-file

is the path to your data file:

my %hash;
my $counter = 0;
open(FILE, "my-text-file");
while (<FILE>) {
 chomp;
 $counter++;
 $hash{$_} = $counter;
}
# Now to sort
foreach $key (sort(keys(%hash))) {
 print $key . ":" . $hash{$key} . "\n";
}

      

I am assuming you want to sort the hash aplaabetically. keys(%hash)

and values(%hash)

return keys and values %hash

as an array, respectively. Run the program in this file:

f
a
b
d
e
c

      

And we get:

a:2
b:3
c:6
d:4
e:5
f:1

      

Hope this helps you.

+2


source







All Articles