Reputation: 4402
I'm trying to substitute all instance of a comma or a hyphen in the string $charlie
. Here is the code I initially tried:
#!/usr/bin/perl
use strict;
use warnings;
my $charlie = "Charlie, 59, 2009";
print "Old Charlie: $charlie\n";
$charlie =~ s/[\,-]/ /;
print "New Charlie: $charlie\n";
This produces the output:
C:\scripts\perl\sandbox>charlie_substitute.pl
Old Charlie: Charlie, 59, 2009
New Charlie: Charlie 59, 2009
As you can tell, only the first comma was replaced by a space. In an attempt to account for multiple commas, I changed the regex to $charlie =~ s/[\,-]{1,2}/ /;
but I still get the same output.
How would I correctly specify the number of occurrences to look for in a substitution?
Upvotes: 1
Views: 69
Reputation: 385935
Use /g
to replace "globally".
$charlie =~ s/[,\-]/ /g;
^
|
(,
isn't special in character classes or even in regex in general, so it doesn't need escaping. On the other, -
can be special in character classes. If anything should be escaped, it's -
. That said, -
doesn't need to be escaped if it's the first or last character of the class as it is here.)
Upvotes: 5