Newbie here. Aplogies if I am missing details.
In perl 5
I have a file that kind of looks like this
precedence = 2
new york
new jersey
florida
precedence = 3
kings
essex
dade
precedence = 1
brooklyn
newark
miami
I have no problem looping through the file and creating a $var that holds the value of precedence and an array (@tmp) that holds the lines until the next "section" (precedence = x)
I need to ultimately push all the sections into a final array in the order of the preference
so
print @final;
results in
brooklyn
.....
new york
.....
kings
.....
NOTE: I never know in advance how many sections there will be or how many lines each section will have
I thought perhapes to make a Hash of hashes and put each array in the HoH
push @{ $hash{"section_2"} }, @tmp ;
but I didnt know
a) if there would be a problem reusing the @tmp array each time i load a section in (after blanking it at the beginning of each loop)
b) I couldnt figure out how to get all values in the array in key "section_2" and push them into @final
Of course there may be a better approach.
An HoH makes no sense. You could use an HoA if you expect a wide variance in precedence levels (1, 1000000, 1000000000),
my $precedence = 0;
my %data;
while (<>) {
chomp;
if (/precedence\s*=\s*([0-9]+)\z/) {
$precedence = $1;
next;
}
push @{ $data{$precedence} }, $_;
}
my @final = map @{ $data{$_} }, sort { $a <=> $b } keys %data;
but an AoA would most likely be a better fit.
my $precedence = 0;
my @data;
while (<>) {
chomp;
if (/precedence\s*=\s*([0-9]+)\z/) {
$precedence = $1;
next;
}
push @{ $data[$precedence] }, $_;
}
my @final = map @$_, grep $_, @data;
Not really sure that I fully understand what you are trying to accomplish but if you want to print each precedence value and then the values from its array, you can try this:
my $hoh;
#This is not how you populate your HoH, I hard code it to simplify
@{$hoh->{2}->{'ARRAY'}} = ('new york', 'new jersey', 'florida');
@{$hoh->{3}->{'ARRAY'}} = ('kings', 'essex', 'dade');
@{$hoh->{1}->{'ARRAY'}} = ('brooklyn', 'newark', 'miami');
foreach my $prcdnc(keys(%$hoh))
{
print "\nprcdnc = ".$prcdnc;
my @prcdncAry = @{$hoh->{$prcdnc}->{'ARRAY'}};
my $prcdncAryStr = join(",", @prcdncAry);
print "\n\t".$prcdncAryStr;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.