Reputation: 71
I have a string,
my $element="abc#$def"
I escape # using,
$element=~s/#/\\#/g;
It is printed as: abc\#$def
, which is perfect.
Next part of the code is:
push(@arr,$element);
foreach $val (@arr)
{
print $val;
}
And the value printed within the foreach loop is: abc#$def
.
Why is #
not escaped here? And how can I retain the escaping?
Upvotes: 1
Views: 83
Reputation: 26861
With something like this:
$element=~s/#/\\#/g;
You have to escape the \
Edit
this code works on my machine as you expect:
use strict;
use warnings;
use Data::Dumper;
my $element='abc#$def';
my @arr;
$element=~s/#/\\#/g;
print $element."\n";
push(@arr,$element);
foreach my $val (@arr)
{
print $val;
}
Upvotes: 0
Reputation: 754590
You're not quite showing us everything. To get your claimed result, I had to create the variable $def
initialized as shown below. But, when I do that, I get the result you expect, not the result you show.
$ cat xx.pl
use strict;
use warnings;
my $def = '$def';
my $element = "abc#$def";
$element =~ s/#/\\#/g;
print "$element\n";
my @arr;
push(@arr, $element);
foreach my $val (@arr)
{
print $val;
print "\n";
}
$ perl xx.pl
abc\#$def
abc\#$def
$
This was tested with Perl 5.14.1 on MacOS X 10.6.8, but I don't think the behaviour would vary with any other version of Perl 5.
Given this, can you update your question to show a script similar to mine (in particular, with both use strict;
and use warnings;
) but which produces the result you show?
Upvotes: 2