Forum Moderators: coopster & phranque

Message Too Old, No Replies

perl question - looping over elements in a hash to find a match

         

jeremy goodrich

8:48 pm on Mar 7, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I figured out why this isn't working, because it goes through once for each value in the keys of the config hash, but since I'm new at hashes, this is giving me some problems wrapping my mind around a way to code it that would work....

Any ideas?

[perl]
foreach $c (keys %config) {
if ($new =~ /$c/) {
print "not adding $c to hash\n";
$c++; }
else { %hash = (%hash, $new, 1);
print "added $new to hash\n";}
$c++; } #ending the foreach $c loop
[/perl]

amoore

9:07 pm on Mar 7, 2002 (gmt 0)

10+ Year Member



It's hard for me to figure out what you're trying to do, but here are some things which may help.

If the obect is to just add $new to the hash if there is not a key that is like it already:


my $found = 0;
foreach my $c ( keys( %hash ) ) {
$found = 1 if ( $new =~ $c );
}
$hash{ $new } = 1 unless $found;

or perhaps something like this:

$hash{ $new } = 1 unless ( grep( /$new/, keys( %hash ) );

You probably don't ever need to increment $c because it is automatically set to each of the keys of the hash by "foreach".
Also, I'm surprised you need to use a regular expression match. It is possible that something like this could work for you:

$hash{ $new } = 1 unless ( defined ( $hash{ $new } ) );

Disclaimer: I haven't checked this for typos and stuff, but the general ideas should be close.

jeremy goodrich

9:32 pm on Mar 7, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



thanks much, that first trick worked perfectly :)

(just started working with hashes a couple days ago, still quite a newbie when it comes to perl...)

Brett_Tabke

9:59 pm on Mar 7, 2002 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



My favorite way to write the same:
[perl]
foreach $c (keys %hash) {
next if $new !~ $c;
$hash{$new}++;
}
[/perl]