Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm having a problem with the following code (the if() statement never executes):
foreach (@banned_channels) {
	if ($channels =~ /$_/i) {
		IRC::print "match: $_";
	}
}
The @banned_channels are loaded from a file (I've verified that this is working fine). I've also made sure that the values of $channel and $_ are both correct on each iteration of the loop. Still, no matches are being made. Am I making some newbie mistake in my use of $_ as a regexp? Oh, if it helps the value of $channels usually looks something like "#help #blah #irc". I suppose I could also post the full source code if the problem seems to be elsewhere. Thanks.
  • Comment on using m// while iterating through an array

Replies are listed 'Best First'.
Re: using m// while iterating through an array
by chromatic (Archbishop) on Sep 22, 2000 at 08:19 UTC
    This works for me:
    #!/usr/bin/perl -w use strict; chomp(my @banned_channels = <DATA>); my $channels = "#gross_people #skriptk1dd13\$ #trolls"; sub IRC::print { print "@_\n"; } foreach (@banned_channels) { if ($channels =~ /$_/i) { IRC::print "match: $_"; } } __END__ #trolls #flamers #lusers #litterbugs
    However, I'd use a hash:
    my $channels = "#gross_people #skriptk1dd13\$ #trolls"; my %banned; @banned{split " ", $channels} = (1); foreach (@banned_channels) { if (exists($banned{$_})) { IRC::print "match: $_"; } }
Re: using m// while iterating through an array
by japhy (Canon) on Sep 22, 2000 at 15:20 UTC
    If you're using a hash, you can probably speed things up by taking a hash slice with @banned_channels as a set of keys:
    my @channels = split / /, '#perl #math #rpi #perlmonks'; my %where; @where{@channels} = @channels; @banned_in = map $_ ? $_ : (), @where{@banned};
    Then again, I could be off my rocker.

    $_="goto+F.print+chop;\n=yhpaj";F1:eval
Re: using m// while iterating through an array
by Anonymous Monk on Sep 22, 2000 at 09:54 UTC
    Wow, thanks for the awesome (and quick) reply. Adding chomp onto the line that reads in the array seems to have been the solution to the problem.