G'day Tmms,
Welcome to the Monastery.
"I am fairly new at perl and I am struggling with references."
Take a look at "perlreftut - Perl references intro"
for general information on references; it contains links to more detailed information - follow as needed.
For general information on data structures, see
"perldsc - Perl data structures intro";
again, this has links to more detailed documentation.
The type of data structure you're attempting to create is called a Hash of Arrays
(typically abbreviated to HoA).
If you look at "Generation of a HASH OF ARRAYS"
(in perldsc),
the last line of the example code is pretty much what you're looking for.
So, working from just your example data, your code would look something like this:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dump;
my %hash;
while (<DATA>) {
chomp;
my ($value, $key) = split /\t/;
push @{$hash{$key}}, $value;
}
dd \%hash;
__DATA__
Obi Wan Jedi
Yoda Jedi
Count Dooku Sith
Output:
{ Jedi => ["Obi Wan", "Yoda"], Sith => ["Count Dooku"] }
While that works fine with your (ideal) example data,
real world data throws up all sorts of nasty challenges.
Whenever you're working with comma- (tab-, pipe-, whatever-) separated values,
I recommend you use the Text::CSV module.
If you also have Text::CSV_XS installed, it will run faster.
This module has addressed these "nasty challenges": this is not a wheel you need to reinvent.
In this instance, the while loop only needs one statement.
#!/usr/bin/env perl
use strict;
use warnings;
use Text::CSV;
use Data::Dump;
my %hash;
my $csv = Text::CSV::->new({sep_char => "\t"});
while (my $row = $csv->getline(\*DATA)) {
push @{$hash{$row->[1]}}, $row->[0];
}
dd \%hash;
__DATA__
Obi Wan Jedi
Yoda Jedi
Count Dooku Sith
Output (exactly the same as before):
{ Jedi => ["Obi Wan", "Yoda"], Sith => ["Count Dooku"] }
See also: Data::Dump (which provides the dd function)
or use Data::Dumper (which is a core module).
|