From: Niall O Broin (niall at domain linux.ie)
Date: Wed 30 May 2001 - 19:54:47 IST
I have a list of numbers in a string like
123,456,789
and I need to find out if any of them begin with 9. This seemed correct
#!/usr/bin/perl
$numlist = $ARGV[0];
if ($numlist =~ /[,^]9/) {
print "$numlist matched\n"
} else {
print "$numlist didn't match\n"
}
but it doesn't work. Now, I have solved my problem. It's Perl, and TIMTOWTDI
as we Perlmongers say. I could have split the string, but I chose to do
if (",$numlist" =~ /,9/)
which works fine. But why won't my program above work ? I had started off
with
if ($numlist =~ /[^,]9/)
but realised (in time, believe it or not) that this was of course a negating
character class. I tried escaping the ^ before I RTFM and simply made the ^
not the first character, as TFM says to do. I also tried \A instead of ^ but
although this works outside of a character class, it does not work as above.
I just tried this with grep too. Given a file, nums, with these lines
123,987 - MATCH
123,456 - NO MATCH
987,123 - MATCH
I think that grep "[,^]9" nums should match the lines marked MATCH but
it doesn't. egrep ",9|^9" nums does match the lines marked MATCH so why
the hell doesn't the alternation work ? What is wrong with my interpretation
of both the grep and the Perl manuals ? (The alternative is that they're
both wrong, and that seems passing unlikely).
Regards,
Niall
This archive was generated by hypermail 2.1.6 : Thu 06 Feb 2003 - 13:10:31 GMT