Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Using map to create a hash/bag from an array

by osunderdog (Deacon)
on Dec 17, 2005 at 10:50 UTC ( #517463=note: print w/ replies, xml ) Need Help??


in reply to Using map to create a hash/bag from an array

Well, it seems to work... So that's certainly a good start. I use two alternatives for this. It depends on whether I need to know the frequency of items or if I need more set like semantics.

Here is the bag example:

use strict; use Data::Dumper; my @items = ('this', 'that', 'that', 'those', 'these', 'them', 'thou') +; my $bag; map {$bag->{$_}++} @items; print Dumper($bag); __END__ $VAR1 = { 'these' => 1, 'those' => 1, 'thou' => 1, 'them' => 1, 'that' => 2, 'this' => 1 };

And here is the set example:

use strict; use Set::Scalar; use Data::Dumper; my @items = ('this', 'that', 'that', 'those', 'these', 'them', 'thou') +; my $set = Set::Scalar->new(@items); print Dumper($set->members); __END__ $VAR1 = 'those'; $VAR2 = 'these'; $VAR3 = 'thou'; $VAR4 = 'them'; $VAR5 = 'that'; $VAR6 = 'this';

Hazah! I'm Employed!


Comment on Re: Using map to create a hash/bag from an array
Select or Download Code
Re^2: Using map to create a hash/bag from an array
by mrborisguy (Hermit) on Dec 18, 2005 at 04:22 UTC

    Why not use for in this example, since you're not really transforming @items into a new array (common use of map), but rather just performing an action for each value in @items (common use of for).

    $bag->{$_}++ for @items; # instead of map {$bag->{$_}++} @items;

        -Bryan

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (12)
As of 2014-11-21 19:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (114 votes), past polls