Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

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

by LanX (Canon)
on Jun 12, 2013 at 21:53 UTC ( #1038599=note: print w/ replies, xml ) Need Help??


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

actually not quite =)

grep { $hash{$_} > 1 } is equivalent to map {$_ if $hash{$_} > 1}

grep {$_ if $hash{$_} > 1} only greps if the key $_ is also true.

Which I agree is very odd code!

Cheers Rolf

( addicted to the Perl Programming Language)


Comment on Re^3: why use a hash instead of an array
Select or Download Code
Re^4: why use a hash instead of an array
by Lotus1 (Chaplain) on Jun 12, 2013 at 22:54 UTC

    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' ]; *******************************************************
      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://1038599]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (8)
As of 2014-10-25 17:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (146 votes), past polls