[plug] Perl Question: Searching an array
Matthew Robinson
matt at zensunni.org
Wed Feb 26 17:11:55 WST 2003
Brad Hill wrote:
> convert the array to a hash and then it's trivial:
You could convert the list to a hash but for a large array this would be
a slow and memory consuming process.
The code that you have shown below does not work as you intend.
>
> #!/usr/bin/perl
>
> @myarray = ( "fish", "chicken", "beef" );
> %myhash = @myarray;
> print "found fash" if $myhash{"fash"};
> print "found fish" if $myhash{"fash"};
I modified your code slightly (shown below), so that it tries to find
fish, chicken and beef and got the following output:
$ perl test.pl
Found fish
$
The code is as shown:
#!/usr/bin/perl
use strict;
my @myarray = ('fish', 'chicken', 'beef');
my %myhash = @myarray;
print "Found fish\n" if ($myhash{fish});
print "Found chicken\n" if ($myhash{chicken});
print "Found beef\n" if ($myhash{beef});
This is because the list ('fish', 'chicken', 'beef') is made into the
following hash structure:
%myhash = (
'fish' => 'chicken',
'beef' => undef
);
This is clearly not what you intended.
Matt
--
print map{s&^(.)&\U\1&&&$_}split$,=$",(`$^Xdoc$,-qj`=~m&"(.*)"&)[0].$/
More information about the plug
mailing list