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' ]; *******************************************************

Replies are listed 'Best First'.
Re^5: why use a hash instead of an array
by LanX (Saint) 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)