What does this Perl statement mean?
I am trying to parse a Perl script in Python. I don’t have any experience with Perl, but it still looks amazingly smooth. Perl's documentation is extensive and impressive. However, from time to time there is some really critical syntax that I really cannot understand and I am unable to communicate with the author of the script. The following has been giving me a headache for several years now:
sub someSubroutine
{
my ($var1, $var2, $var3) = @_;
# some Perl code
$var2 =~ s|/|\\|g;
# and then some more code ..
}
I really don't get this special and lonely line
$dst =~ s|/|\\|g;
I understand that it does search / string match in $var2
with some binary OR operations, but the result is not saved.
I wonder if it has any less obvious side effects, like it automatically gets saved to $_
?
From what I've read, the default variables are set automatically when you call a subroutine, initiate a loop or similar, but don't know anything about when you use statements.
I would really appreciate any help or pointers to relevant documentation.
source to share
IN
$var2 =~ s|/|\\|g;
s/pattern/replacement/
is the replacement operator ...
Searches for a string for a pattern, and if found, replaces that pattern with replacement text and returns the number of substitutions made. Otherwise, it returns false (in particular, an empty string).
|
is not "binary" or "is a delimiter. In s
you can use any delimiter, especially for readability.
from perlop
Regexp Quote-Like Operators
Any separator without spaces can replace forward slashes. Add space after s when using a character allowed in identifiers. If single quotes are used, interpretation is not performed on the replacement string (the / e modifier overrides this, however). Note that Perl handles backward normal delimiters; replacement text is not evaluated as a command. If the PATTERN value is limited to bracketed quotes, REPLACE its own quotes pairs, which may or may not be parentheses for e.g. s (foo) (bar) or s / bar /.
The above replaces every /
on \
in $var2
. ( \
is an escape character, so you need to use \\
).
my $v='/a/b/c';
$v =~ s|/|\\|g;
print "$v\n";
# \a\b\c
Besides,
If no lines are specified using the ~ ~ or! ~, variable $ _ is searched and modified.
$_ = $v; # assign the $_
s{\\}{/}g; # substitution on the $_ using bracketed delimiters
print; # without args prints the $_
# /a/b/c
source to share