Created
July 5, 2013 16:18
-
-
Save jadeallenx/5935623 to your computer and use it in GitHub Desktop.
Perl complex data structures example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use 5.010; | |
use warnings; | |
use strict; | |
use Data::Dumper; | |
# If you have access to CPAN, check out Data::Printer | |
# https://metacpan.org/module/Data::Printer | |
## build a list of hashes | |
my @list_of_hashes; | |
push @list_of_hashes, { foo => "bar", 1 => "hi", }; | |
## iterate over list; there is more than one way to do this, naturally | |
foreach my $hash ( @list_of_hashes ) { | |
foreach my $key ( keys %{ $hash } ) { | |
say "key: $key => value: $hash->{$key}"; | |
} | |
} | |
## build a hash of hashes | |
my %hash_of_hashes; | |
$hash_of_hashes{"some_key"} = { hello => "world!" }; | |
say Dumper %hash_of_hashes; | |
# or | |
my $hash_ref; | |
$hash_ref->{"some_key"} = { hello => "world!" }; | |
say Dumper $hash_ref; | |
say $hash_ref->{"some_key"}->{"hello"}; | |
# build a hash of lists of lists | |
# | |
# yes, you can keep going on this if you want, but it might be silly | |
my %hash_of_lists; | |
push @{ $hash_of_lists{"some_key"} }, [ "foo", "bar", 1 ]; | |
# prints a list with sublist 'foo', 'bar', 1 | |
say Dumper $hash_of_lists{"some_key"}; | |
# prints 'bar' | |
say $hash_of_lists{"some_key"}[0]->[1]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment