[plug] Perl Question: Searching an array
Tony Breeds
magni at plug.linux.org.au
Wed Feb 26 17:26:17 WST 2003
On Wed, Feb 26, 2003 at 04:50:37PM +0800, Brad Hill wrote:
> convert the array to a hash and then it's trivial:
>
> #!/usr/bin/perl
>
> @myarray = ( "fish", "chicken", "beef" );
> %myhash = @myarray;
> print "found fash" if $myhash{"fash"};
> print "found fish" if $myhash{"fash"};
This won't quite do what you want. It will make a hash where
$myhash{fish}=chicken;
and
$myhash{beef}=undef;
---
#!/usr/bin/perl
@myarray = ( "fish", "chicken", "beef" );
%myhash = @myarray;
print "found fash" if $myhash{"fash"};
print "found fish" if $myhash{"fish"};
print "found chicken" if $myhash{"chicken"}; <== this wont be there.
print "\n";
---
David, You can either do as Brad suggested and do
---
@myarray = ( "fish", "chicken", "beef" );
%myhash = map {$_,1} @myarray;
print "found fash" if $myhash{"fash"};
print "found fish" if $myhash{"fish"};
print "found chicken" if $myhash{"chicken"};
---
or use grep;
grep /$search_val/ @myarray;
Changing your code slightly you can do:
---
$search_val = "text-to-look-for";
$found='false';
foreach $line ( @myarray ) {
if ( $search_val eq $line ) {
$found = "true";
last;
}
}
---
This will stop executing the foreach loop after the first match.
Little tip "==" is for numerics "eq" is for strings.
Neither of these options is particulaly memoriy efficient for large
arrays tho. This code is "better" in terms of memory footprint, prolly
suffers on speed tho :(
---
$search_val = "text-to-look-for";
$found='false';
for(my$i=0;$i<=$#myarray;$i++) {
if ( $search_val eq $myarray[$i] ) {
$found = "true";
last;
}
}
---
Is better as it doesn't pass a _copy_ of the list in foreach.
Yours Tony
More information about the plug
mailing list