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

Re: array => hash of occurrence indexes

by kcott (Archbishop)
on Sep 12, 2013 at 05:19 UTC ( [id://1053646]=note: print w/replies, xml ) Need Help??


in reply to array => hash of occurrence indexes

G'day pldanutz,

I generally think it's better to pass around scalars than entire data structures, so returning a reference to that hash would be my preference.

If you wrapped $h{$k} in @{...}, you could dispense with if (! $h {$k}) { $h {$k} = [] } entirely.

Even if you're using 5.012 for other reasons elsewhere in your code, I see little, if any, value in using each here. It's easy to write it for any Perl5.

Putting all that together, you could code occurrences() like this instead:

sub occurences { my %h; my $i = 0; push @{$h{$_}}, $i++ for @_; return \%h; }

If you were looking for a golf answer, you could start with the following and then proceed to remove whitespace until illegibility was achieved. :-)

sub occurences { my ($i, %h) = 0; push @{$h{$_}}, $i++ for @_; \%h }

Here's my tests:

$ perl -Mstrict -Mwarnings -e ' use Data::Dumper; sub occurences { + my %h; my $i = 0; push @{$h{$_}}, $i++ for @_; return \%h; } my $h = occurences(2, 1, 3, 4, 3, 4, 4, 5); print Dumper $h; ' $VAR1 = { '1' => [ 1 ], '3' => [ 2, 4 ], '2' => [ 0 ], '4' => [ 3, 5, 6 ], '5' => [ 7 ] };
$ perl -Mstrict -Mwarnings -e ' use Data::Dumper; sub occurences { my ($i, %h) = 0; push @{$h{$_}}, $i++ for @_; \%h + } my $h = occurences(2, 1, 3, 4, 3, 4, 4, 5); print Dumper $h; ' $VAR1 = { '4' => [ 3, 5, 6 ], '1' => [ 1 ], '5' => [ 7 ], '2' => [ 0 ], '3' => [ 2, 4 ] };

-- Ken

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (3)
As of 2024-04-19 05:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found