in reply to Re: Regex and negative file test
in thread Regex and negative file test

Your alternation \$|&|<|>|@|\/ would be better expressed as a character class [$&<>@/].

Not really, no:

use strict; use warnings; my $name = 'whatever'; print $name =~ /[$&<>@/]/ ? 'Yep!' : 'Nope!';

Output:

Unmatched right square bracket at C:\Perl\progs\junk.pl line 5, at end + of line syntax error at C:\Perl\progs\junk.pl line 5, near "/[$&<>@/]" Search pattern not terminated or ternary operator parsed as search pat +tern at junk.pl line 5.

Drat! Let's escape that pesky slash:

my $name = 'whatever'; print $name =~ /[$&<>@\/]/ ? 'Yep!' : 'Nope!';

Output:

Use of uninitialized value in concatenation (.) or string at junk.pl l +ine 5. Nope!

What's happening now? Ah, perl seems to think that $& means $MATCH. Why can't it DWIM? Let's try this:

my $name = 'whatever'; print $name =~ /[&$<>@\/]/ ? 'Yep!' : 'Nope!';

Aah, that's better!

Update: fixed typo, closed blockquote tag.

Update 2: just realised that there's yet another problem. The dollar sign has to be escaped as well:

my $name = 'what$ever'; print $name =~ /[\$&<>@\/]/ ? 'Yep!' : 'Nope!';

Replies are listed 'Best First'.
Re^3: Regex and negative file test
by johngg (Canon) on Dec 06, 2006 at 23:09 UTC
    Yes, that was stupid of me. Thank you for pointing out my error.

    Part of it is that I always use m{ ... } rather than / ... / so I have lost the habit of escaping slashes. The other part is I didn't realise that there was interpolation inside a character class so, as you point out, I failed to escape the $. Ought to do the @ as well, I suppose. Not sure about the &?

    $ perl -le ' > use strict; use warnings; > print q{whatever} =~ m{[\$&<>\@/]} ? q{Yep} : q{Nope};' Nope $ perl -le ' > use strict; use warnings; > print q{v$table} =~ m{[\$&<>\@/]} ? q{Yep} : q{Nope};' Yep $ perl -le ' > use strict; use warnings; > print q{bill@bloggs.com} =~ m{[\$&<>\@/]} ? q{Yep} : q{Nope};' Yep $

    Cheers,

    JohnGG

      Ought to do the @ as well, I suppose. Not sure about the &?

      Neither am I. We could start a long discussion here involving eg quotemeta. But I suggest that we go no further down this line, and just accept to follow Corion's excellent advice above :

      ...it is a much saner approach to only allow what is permitted instead of rejecting what you know is bad.