Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Making a hash of arrays using references

by NetWallah (Canon)
on Apr 09, 2017 at 06:23 UTC ( [id://1187508]=note: print w/replies, xml ) Need Help??


in reply to Making a hash of arrays using references

You will find this a frequent code pattern, young padewan.

Here is a self-contained solution that demonstrates the idioms.

This code uses "Autovivification" to avoid the issue you experienced - i.e. the same code handles both the case where the key is absent, and when present. Read all about it in perlref.

use strict; use warnings; my %team; while (defined (my $line=<DATA>)){ chomp $line; # Zap the newline my ($name,$affiliation) = split /\t/,$line; next unless $affiliation; # Avoid empty lines push @{ $team{$affiliation} }, $name; } # Print the results for my $aff (sort keys %team){ print $aff, " :\t", join(", ", sort @{ $team{$aff} }) , "\n"; } __DATA__ Obi Wan Jedi Yoda Jedi Count Dooku Sith Darth Vader Sith Luke Skywalker Jedi
OUTPUT:
Jedi : Luke Skywalker, Obi Wan, Yoda Sith : Count Dooku, Darth Vader

        ...it is unhealthy to remain near things that are in the process of blowing up.     man page for WARP, by Larry Wall

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1187508]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (7)
As of 2024-04-19 15:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found