Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this Perl statement mean?

Tags:

operators

perl

I'm trying to parse a Perl script to Python. I have next to no experience with Perl, but still it's going surprisingly smooth. The Perl documentation is vast and impressive. However, from time to time there are some really cryptic syntax I really can't figure out and I'm not in a position of communicating with the author of the script. The following has given me a headache for quite some time now:

sub someSubroutine
{
    my ($var1, $var2, $var3) = @_;

    # some Perl code

    $var2 =~ s|/|\\|g;

    # and then some more code ..
}

I really don't get this one particular and lonely line

$dst =~ s|/|\\|g;

I'm clear that it makes a search/string-match in $var2 with some binary OR operations, but the result is not stored.

I wonder if it has any not so apparent side effects, for instance is it automatically stored in $_?

From what I've read, the default variables are set automatically when one calls a subroutine, initiates a loop or similar, but nothing about when using operators.

I would really appreciate any help or pointers to appropriate documentation.

like image 523
Wololo Avatar asked Sep 14 '26 21:09

Wololo


1 Answers

In the

$var2 =~ s|/|\\|g;

the s/pattern/replacement/ is the substitution operator.

Searches a string for a pattern, and if found, replaces that pattern with the replacement text and returns the number of substitutions made. Otherwise it returns false (specifically, the empty string).

The | isn't "binary or" - it is a delimiter. In the s you can use any delimiter, especially for easier reading.

from the perlop Regexp Quote-Like Operators

Any non-whitespace delimiter may replace the slashes. Add space after the s when using a character allowed in identifiers. If single quotes are used, no interpretation is done on the replacement string (the /e modifier overrides this, however). Note that Perl treats backticks as normal delimiters; the replacement text is not evaluated as a command. If the PATTERN is delimited by bracketing quotes, the REPLACEMENT has its own pair of quotes, which may or may not be bracketing quotes, for example, s(foo)(bar) or s/bar/.

The above replaces every / with \ in the $var2. (The \ is escape character, therefore you need use \\).

my $v='/a/b/c';
$v =~ s|/|\\|g;
print "$v\n";
# \a\b\c

Also,

If no string is specified via the =~ or !~ operator, the $_ variable is searched and modified.

$_ = $v;     # assign the $_
s{\\}{/}g;   # substitution on the $_ using bracketed delimiters
print;       # without args prints the $_
# /a/b/c
like image 199
jm666 Avatar answered Sep 16 '26 22:09

jm666