Click to See Complete Forum and Search --> : How do you check if a value is already in an array?
henryh
08-25-2004, 12:31 PM
Hello, just wondering, how do you check if a value is already in an array?
Situation is I have alotta files with names that have the date in em, and I want to get all the different years there are, which is the first part of the filename. There are alotta files with the same years.
Thanks for reading and for any help given.
henryh
08-25-2004, 12:35 PM
meant to say i didn't want repeats of years, sorry.
silent11
08-25-2004, 01:28 PM
my %unique;
foreach my $thingy (@array_with_duplicates)
{ $unique{$thingy} = 1; }
my @array_without_duplicates = keys %unique;
code by jcpunk
Nedals
08-27-2004, 12:28 AM
silent11..
That's a neat bit of code but I don't think it solves the problem.
I want to get all the different years there are, which is the first part of the filename.
my @filename = qw(2000abc 2001abc 2000bcd 2001bcd 2000cde 2001cde);
So I think the result should be (2000,2001)
my %unique;
foreach my $thingy (@array_with_duplicates)
$thingy =~ s/^(\d+).*$/$1/; # assumes that the year is followed by one or more letters
{ $unique{$thingy} = 1; }
my @array_without_duplicates = keys %unique;
If name can be all numeric and the first 4 digits represent the year, change (\d+) to (\d{4})
meant to say i didn't want repeats of years, sorry.
There again, maybe not :)
cyber1
09-02-2004, 10:49 PM
Try this:
%seen=();
@unique=();
foreach $year (@filename){
$year =~ m/^(\d+)/;
unless($seen{$1}){
$seen{$1} = 1;
push(@unique, $1);
}
}
print qq|unique:@unique\n|;