in reply to Re: without looping, check if $var is found in @list
in thread without looping, check if $var is found in @list
It will fail (false positive or false negative) if $var contains regexp characters.
my $var = 'tad?pole'; my @list = ($var); print("@list" =~ /\b$var\b/ ? 1 : 0, "\n");
It will fail (false negative) if $var starts or ends with \W (because \b won't match).
my $var = 'frog!'; my @list = ($var); print("@list" =~ /\b$var\b/ ? 1 : 0, "\n");
It will fail (false positive or false negative) if $var contains spaces. (Credit goes to duckyd.)
my $var = 'turtle'; my @list = ("jumping $var"); print("@list" =~ /\b$var\b/ ? 1 : 0, "\n");
If you knew a specific character will not be present in @list, you could use that character as a seperator.
my $sep = "\x01"; my @list = ('jumping turtle', 'frog!', 'tad?pole'); for my $var (@list) { if (join($sep, '', @list, '') =~ /\Q$sep$var$sep\E/) { print "Found $var\n" } else { print "Didn't find $var\n" } }
You could even make it faster by using index.
my $sep = "\x01"; my @list = ('jumping turtle', 'frog!', 'tad?pole'); for my $var (@list) { if (index(join($sep, '', @list, ''), "$sep$var$sep") >= 0) { print "Found $var\n" } else { print "Didn't find $var\n" } }
But really, are either of those solutions anywhere near as readable as those already suggested? That's without even taking into account the limitation of disallowing $sep from being in @list.
Update: A few small corrections: Removed extra parens, fixed third snippet.
|
|---|