NewLearner
NewLearner

Reputation: 223

Perl - Associative Array with index

Ok, I'm new to Perl but I thins this question is for Perl Gurus only :)

I need a well explain example of how to store and keep control of data read from a file. I want to store them using an Associative array with index and then use a for loop to go over the array and print it to the screen. For example:

 my %array;

$array{$1} = [0]

foreach $array (sort values $array)
 print "$value";

Something like this.

Upvotes: 0

Views: 2686

Answers (3)

TLP
TLP

Reputation: 67900

You most likely do not want to use a hash (associative array is not a perl construct any longer) at all. What you are describing is using an array. Hashes are used for storing data connected with unique keys, arrays for serial data.

open my $fh, "<", $inputfile or die $!;
my @array = <$fh>;
print @array;  # will preserve the order of the lines from the file

Of course, if you want the data sorted, you can do that with print sort @array.

Now, if that had been done with a hash, you'd do something like:

my %hash = map { $_ => 1 } <$fh>;
print sort keys %hash; # will not preserve order

And as you can see, the end result is only that you do not preserve the original order of the file, but instead have to sort it, or get a semi-random order. All the while, you're running the risk of overwriting keys, if you have identical lines. This is good for de-duping data, but not for true representation of file content.

You might think "But hey, what if I use another kind of key and store the line as the value?" Well, sure, you might take JRFerguson's advice and use a numerical index. But then you are using an array, just forsaking the natural benefits of using a proper array. You do not actually gain anything by doing this, only lose things.

Upvotes: 1

Sebastian Stumpf
Sebastian Stumpf

Reputation: 2791

Or even easier via the slurp method from IO::All:

@lines = io('file.txt')->slurp;

If you are reading a larger file you will probably want to lock the file to prevent racing conditions and IO::All makes it really easy to lock files while you are working with them.

Upvotes: 1

JRFerguson
JRFerguson

Reputation: 7516

First, Perl refers to associative arrays as "hashes". Here's a simple example of reading the lines of a file and storing them in a hash to print them in reverse order. We use the line number $. of the file as the hash key and simply assign the line itself ($_) as the hash value.

#!/usr/bin/env perl
use strict;
use warnings;
my %hash_of_lines;
while (<>) {
    chomp;
    $hash_of_lines{$.} = $_;
}
for my $lineno ( sort { $b <=> $a } keys %hash_of_lines ) {
    printf "%3d %s\n", $lineno, $hash_of_lines{$lineno};
}

Upvotes: 2

Related Questions