Perl: Why is the position of `[:space:]` within a character class seemingly important?
04:31 12 Dec 2025

I'd like to use constants to build regular expressions. However, in this case I got an unexpected syntax error:

me:~> cat foo.pl
#!/usr/bin/perl
use strict;
use warnings;

use constant CR_SAFE    => '[:alnum:]@,._\-!%=';

# quote argument if needed
sub cond_quote($)
{
    my $arg = shift;

    return $arg
        if ($arg =~ /^[${\CR_SAFE}]+$/);
    $arg =~ s/[^${\CR_SAFE}[:space:]]/\\$&/g;
    return '"' . $arg . '"';
}
me:~> perl -c ./foo.pl
syntax error at ./foo.pl line 14, near "[:"
./foo.pl had compilation errors.

However if I move [:space:] before expanding the constant ($arg =~ s/[^[:space:]${\CR_SAFE}]/\\$&/g;), then I get no syntax error.

Don't I see the obvious, or who can explain?

perl syntax