Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: How to connect more arrays to a new array

by samurai (Monk)
on Apr 28, 2003 at 02:22 UTC ( [id://253573]=note: print w/replies, xml ) Need Help??


in reply to Find unique elements from multiple arrays

Hashes are the best data structures to use when trying to create arrays with unique values, because the keys are guaranteed to be unique (duplicate keys are overwritten as opposed to being appended to the stack). When you start using hashes to do lookups for uniqueness, you've learned a valuable skill. Here's some commented code for how to do this:

# your arrays my @a = qw(a c d); my @b = qw(s d v); my @c = qw(l d s); my @d = qw(i c f); # the hash we'll use to preserve uniqueness my %unique = (); # for every character in each of the defined arrays for my $char (@a, @b, @c, @d) { # whenever we run into a character, we set its # corresponding value to 1 in the unique hash. Even if we # run into the same character more than once, it'll only have # a single entry in our hash, as is the nature of hashes. $unique{$char} = 1; } # now, the keys in the %unique hash should be the unique # values from those arrays. We'll sort the keys for good # measure my @unique = sort keys %unique; # @unique is now the unique elements of those arrays. Kudos.

Hashes are your friend (I use them a LOT when looking for duplicates in company data files). Learn to use them wisely and you'll appreciate perl's power and simplicity a lot sooner.

Or, for a quickie:

my %unique = map { $_=>1 } @a, @b, @c, @d; my @unique = sort keys %unique;

--
perl: code of the samurai

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (4)
As of 2024-03-29 12:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found