Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re^4: why use a hash instead of an array

by Lotus1 (Chaplain)
on Jun 12, 2013 at 22:54 UTC ( #1038611=note: print w/ replies, xml ) Need Help??


in reply to Re^3: why use a hash instead of an array
in thread why use a hash instead of an array

It looks like we were both wrong. None of them are equivalent. ;)

use strict; use warnings; use Data::Dumper; my %hash; while(<DATA>){ #chomp; $hash{$_}++ for split; } $hash{''}=2; print Dumper(\%hash); print '*'x55,"\n"; my @greparr= grep {$hash{$_} > 1} sort keys %hash; print "greparr has ", scalar @greparr, " elements.\n"; my @maparr = map {$_ if $hash{$_} > 1} sort keys %hash; print "maparr has ", scalar @maparr, " elements.\n"; my @grep2 = grep {$_ if $hash{$_} > 1} sort keys %hash; print "grep2 has ", scalar @grep2, " elements.\n"; print '*'x55,"\n"; print Dumper(\@greparr); print '*'x55,"\n"; print Dumper(\@maparr); print '*'x55,"\n"; print Dumper(\@grep2); print '*'x55,"\n"; __DATA__ 0 0 teacher students teacher students nope

Output:

$VAR1 = { '' => 2, '0' => 2, 'nope' => 1, 'students' => 2, 'teacher' => 2 }; ******************************************************* greparr has 4 elements. maparr has 5 elements. grep2 has 2 elements. ******************************************************* $VAR1 = [ '', '0', 'students', 'teacher' ]; ******************************************************* $VAR1 = [ '', '0', '', 'students', 'teacher' ]; ******************************************************* $VAR1 = [ 'students', 'teacher' ]; *******************************************************


Comment on Re^4: why use a hash instead of an array
Select or Download Code
Re^5: why use a hash instead of an array
by LanX (Canon) on Jun 12, 2013 at 23:09 UTC
    thanks for testing, I was too lazy! =)

    The standard for "Map as Grep" is to take ternary to define the false case too, and this for good reasons...

    Though I'm not sure why if returns an empty string "" and not an empty list () when false.

    DB<141> $x = do { "---" if 0>0 } => "" DB<142> "<$x>" => "<>"

    Cheers Rolf

    ( addicted to the Perl Programming Language)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2014-09-17 01:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (56 votes), past polls