Hello dirtdog,
You do not need to push into an array the @ARGV it is a already an array. Sample of code bellow:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $count = 0; my %hasHierarchy; $hasHierarchy{$_} = $count++ foreach @ARGV; while( my( $key, $value ) = each %hasHierarchy ){ print "$key: $value\n"; } # print Dumper \%hasHierarchy; __END__ $ perl test.pl POPE PATRIARCH ARCHBISHOP CARDINAL POPE: 0 CARDINAL: 3 ARCHBISHOP: 2 PATRIARCH: 1
You can also use Data::Dumper to view complex structures. On the sample of code I have enter the command remove the # and give it a try.
Update: Just a minor note to add, you can use also while loop to process the @ARGV, usually while loops are faster than foreach loops. Have a look on the Benchmark bellow, but also keep in mind that the while loop because we are using shift we will destroy the array. In case you want to reuse the array you need to copy it. In this case foreach loop is faster so a better option. :)
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; # use Benchmark qw(:all) ; # WindowsOS use Benchmark::Forking qw( timethese cmpthese ); # UnixOS sub whileLoop { my $localCount = 0; my %localHasHierarchy; while (defined(my $input = shift (@_))) { $localHasHierarchy{$input} = $localCount++; } return \%localHasHierarchy; } sub foreachLoop { my $localCount = 0; my %localHasHierarchy; $localHasHierarchy{$_} = $localCount++ foreach (@_); return \%localHasHierarchy; } # print Dumper whileLoop(@ARGV); # print Dumper foreachLoop(@ARGV); my $results = timethese(-10, { 'While' => sub { whileLoop(@ARGV) }, 'Foreach' => sub { foreachLoop(@ARGV) } }, 'none'); cmpthese( $results ); __END__ $ perl test.pl POPE PATRIARCH ARCHBISHOP CARDINAL Rate While Foreach While 719936/s -- -19% Foreach 889776/s 24% --
Update 2: I tried to apply minor modifications but still foreach is winning, but at least now they are closer on the comparison. :)
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; # use Benchmark qw(:all) ; # WindowsOS use Benchmark::Forking qw( timethese cmpthese ); # UnixOS sub whileLoop { my $localCount = 0; my %localHasHierarchy; while (defined($_ = shift (@_))) { $localHasHierarchy{$_} = $localCount++; } return \%localHasHierarchy; } sub foreachLoop { my $localCount = 0; my %localHasHierarchy; $localHasHierarchy{$_} = $localCount++ for (@_); return \%localHasHierarchy; } # print Dumper whileLoop(@ARGV); # print Dumper foreachLoop(@ARGV); my $results = timethese(-10, { 'While' => sub { whileLoop(@ARGV) }, 'Foreach' => sub { foreachLoop(@ARGV) } }, 'none'); cmpthese( $results ); __END__ $ perl test.pl POPE PATRIARCH ARCHBISHOP CARDINAL Rate While Foreach While 739404/s -- -17% Foreach 893518/s 21% --
Hope this helps, BR.
In reply to Re: HASH Hierarchy
by thanos1983
in thread HASH Hierarchy
by dirtdog
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |