Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: How can I assign the elements in an array to only the key values in a hash?

by stefp (Vicar)
on Mar 31, 2001 at 20:59 UTC ( [id://68671]=note: print w/replies, xml ) Need Help??


in reply to How can I assign the elements in an array to only the key values in a hash?

Q: I have an array that keeps returning matches in a string, each match must be inserted into a hash as an empty key (..)

If i judge by your code, you want empty values. Anyway empty keys does not make sense. Because each key of a hash must be unique within the hash set of keys

$hash{$_}=  '' for @array;

usually conunting number of matches for each strings makes more sense:

$hash{$_}++ for @array;

-- stef

Replies are listed 'Best First'.
Re: Answer: How can I assign the elements in an array to only the key values in a hash?
by Benedictine Monk (Novice) on Apr 01, 2001 at 08:47 UTC

    If you're just trying to remove duplicates from the array (which I'm not sure you are), you can do this:

    my @array = getMatches();
    my %tmp;
    @tmp{@array} = (undef) x @array;
    @array = keys %tmp;
    undef %tmp;
    

    This takes advantage of Perl's hash slices and can be incredibly useful for set-like operations.

    Jerry Goure

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (2)
As of 2024-04-25 20:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found