Marcus
Marcus

Reputation: 5838

Why is the # character seen as a 'word' character in Perl?

Why is the # character seen as a 'word' character in Perl? Or am I misunderstanding how this code is supposed to work?

#!/usr/bin/perl

my $filename = "Something_with_#_sign.jpg";

$filename =~ s/        # substitute...
                [^             # characters which are NOT:
                \w                # "word" characters
                ]              # end of character classes
                /_/xg;     # ...with an underscore

print "$filename\n";

Yields:

Something_with_#_sign.jpg

I would have expected the # sign to have been replaced by an _ (underscore).

Upvotes: 4

Views: 92

Answers (1)

ikegami
ikegami

Reputation: 386396

/x doesn't modify the syntax of character classes (or of \x20, or of s{3,4}, etc, etc), so

[^             # characters which are NOT:
\w                # "word" characters
]              # end of character classes

is a weird way of writing

[^ "#:NOTacdefhilnorst\n\w]

Upvotes: 10

Related Questions