Reputation: 969
I'm stuck on this problem for days and don't know which data structure I should use in Perl
Suppose I have this file with the following inputs:
lookup hello
lookup good night
good night
I want to be able to store "lookup" linked with "hello", "lookup" linked with "good night" and lastly "good night" linked with nothing else. Should I use a hash or an array? If I set "lookup" as the key of the hash, I will lose "hello" information. If I set "good night" as key, I will end up losing the 3rd line of information.
What should I do?
EDIT: There are certain keywords (which I called "lookup") that has stuff that are linked to them. For example, "password" will be followed by the actual password whereas "login" need not have anything following it.
Upvotes: 0
Views: 96
Reputation: 23
You could also use a hash of hashes if you plan to store another piece of data with your linked "lookup"->"good night" which will be easy to access later on. E.g:
%result = (
'lookup' => {
'hello' => $storage1,
'good night' => $storage2,
},
'good night' => {
}
);
Upvotes: 0
Reputation: 91385
Not quite sure what you want, but, is this ok:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dump qw(dump);
# build a hash of keywords
my %kword = map{ $_ => 1}qw(lookup kword1 kword2);
my %result;
while(<DATA>) {
chomp;
my ($k, $v) = split(/ /,$_, 2);
push @{$result{$k}}, $v if exists $kword{$k};
}
dump%result;
__DATA__
lookup hello
lookup good night
good night
kword1 foo
kword1 bar
output:
("kword1", ["foo", "bar"], "lookup", ["hello", "good night"])
Upvotes: 0
Reputation: 212248
It looks like you want a hash of arrays. Ignoring the issue of how to decide the key is "good night" instead of "good" (and just assuming the key should be "good"), you could do something like:
#!/usr/bin/env perl use strict; use warnings; my %hoa; # hash of arrays while(<>) { my @f = split; my $k = shift @f; $hoa{ $k } = [] unless $hoa{ $k }; push @{$hoa{ $k }}, join( ' ', @f ); } foreach my $k( keys( %hoa )) { print "$k: $_\n" foreach ( @{$hoa{ $k }}); }
Upvotes: 1
Reputation: 15063
It's not exactly clear how you're expecting to break up the words here, but in the general case, if you need to do random lookups (by arbitrary word), a hash is a better fit than an array. Without additional details on exactly what you're trying to do here, it's hard to be more specific.
Upvotes: 1