http://qs1969.pair.com?node_id=545520


in reply to Re: delayed variable interpolation in a regular expression
in thread delayed variable interpolation in a regular expression

I've always thought that the first position was for the closing square bracket, and the hyphen should be placed at the end of the character class. From perlretut: If ’-’ is the first or last character in a character class, it is treated as an ordinary character; "[-ab]","[ab-]" and "[a\-b]" are all equivalent. It's interesting to note that the same doesn't apply to the closing square bracket:

$ perl -e 'my $s="-]"; print "a\n" if $s =~ /[___]]/' $ perl -e 'my $s="-]"; print "a\n" if $s =~ /[]___]/' a $ perl -e 'my $s="-]"; print "a\n" if $s =~ /[___-]/' a $ perl -e 'my $s="-]"; print "a\n" if $s =~ /[-___]/' a

Update: In Perl, ']' has to be escaped so the first and seconds examples above are wrong. It is in grep, where it suffices to put the bracket at the beginning of the character class.

--
David Serrano

Replies are listed 'Best First'.
Re^3: delayed variable interpolation in a regular expression
by SamCG (Hermit) on Apr 25, 2006 at 16:03 UTC
    David, you were correct the first time and your second example is fine. ] can be the first character in a class without being escaped.

    H:\>perl -e "$_='a';/[]a]/?print 'Y':print 'N'" Y H:\>
    On an XP box (which is why you see the reversed quote notation). I also believe you're absolutely correct about the hyphen being acceptable as the last character (it's not "underscore to nothing").


    -----------------
    s''limp';@p=split '!','n!h!p!';s,m,s,;$s=y;$c=slice @p1;so brutally;d;$n=reverse;$c=$s**$#p;print(''.$c^chop($n))while($c/=$#p)>=1;
Re^3: delayed variable interpolation in a regular expression
by johngg (Canon) on Apr 25, 2006 at 10:34 UTC
    I thought it had to be first but obviously I was wrong. Apologies to wannabeperlie. Thank you for the correction. Another new thing learnt.

    Cheers,

    JohnGG