At 11:15 PM -0600 1/8/12, Chris Stinemetz wrote:
How do I extract uniq elements from an array? Basically I want to
preserve the order of the elements as they are first seen, but I would
like to remove any duplicates.
Use a hash to keep track of elements. Create an entry in the hash
with the element as a key. The first time the element is encountered,
the hash entry will not exist. Every subsequent time, it will. You
can set a true value for the hash entry and just test for truthiness,
as accessing the hash with a key that does not exist in the hash
returns under, which tests as false. You can also use the exists
function on the hash.
Below is what I have so far.
Thank you in advance.
Chris
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
my @header;
while( <DATA> ) {
chomp;
if($_ =~ /(.*)\=(.*)?/) { will use $2 for later.
@header = $1;
Assigning a scalar value to a list makes no sense. You will get a
list with the scalar as a single element, but that cannot be what you
want. You want to add the scalar to the list:
push(@header,$1);
Count the element using a hash this way (%seen should be declared
before the loop):
$seen{$1}++;
If an element appears more than once, the count will be greater than
one. You can either check at the end, or check in the loop and not
add the element to the array if $seen{$1} already exists (with the
value 1).
print Dumper \@header;
Print your array after the loop has terminated to find out what is in
it at the end.
}
}
__DATA__
csno=1
rfpi=1
vrp0=3423000
vrp1=3423000
trl=1700000
low=
high=5
csno=1
rfpi=2
vrp0=3423000
vrp1=3423000
trl=1700000
row[1]=
row[2]=
row[3]=
line=
low=
high=5
csno=1
rfpi=3
vrp0=3423000
vrp1=3423000
trl=1700000
line=
low=
line[1]=
line[2]=
high=5
low=
--
Jim Gibson
j...@gibson.org
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/