Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: A C-like brain in a Perl-like world

by ducky (Scribe)
on Sep 26, 2001 at 23:49 UTC ( [id://114924]=note: print w/replies, xml ) Need Help??


in reply to A C-like brain in a Perl-like world

Of course TMTOWTDI (variation on tachyon's theme, really):

sub unique_merge { my ( %hash ) = map {$_ => 1 } @_ ; return keys %hash } my @array1 = qw(a b c d e) ; my @array2 = qw(c d e f) ; my @merged_array = unique_merge(@array1, @array2) ;

Hashes may only have one key per value, so the task becomes how to get make a hash out of an array (or two). Using map I turn the arrays into key/value pairs (the value is not so important) and then ask for the keys back.

HTH

-Ducky

Replies are listed 'Best First'.
Re (tilly) 2: A C-like brain in a Perl-like world
by tilly (Archbishop) on Sep 27, 2001 at 00:01 UTC
    Using keys in this way causes stringification of values. If your arrays have objects or references in them, this will bite. Also note that that 2 for 1 map was slow until Perl 5.6.1. The following is therefore how I do that:
    sub unique_merge { my %seen; grep !$seen{$_}++, @_; }
    Side benefit? I don't lose the order of the incoming elements. :-) But, as with all hash approaches, my definition of "unique" is "stringifies the same". That is not always the appropriate definition to use.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (7)
As of 2024-03-28 09:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found