开发者

What does s-/-- and s-/\Z-- in perl mean?

I am a beginner in perl and I have a query regarding pattern matching. I came across a line in perl where it was written

  $variable =~ s-/\Z--;

And as the code goes ahead some another variable was assigned

  $variable1 =~ s-/--;

Can you please tell me wh开发者_C百科at does these 2 lines do? I want to know what does s-/\Z-- and s-/-- mean.


$variable =~ s-/\Z--;

- is used as a delimiter here. However, best practice suggests that you either use / or {} as delimiters.

It could be re-written as:

$variable =~ s{/\Z}{};  # remove a / at the end of a string

Consider:

$variable1 =~ s-/--;

Again, it could be re-written as:

$variable1 =~ s{/}{};  # remove the first /


The s/// operator in Perl is a substitution operation, which performs a search-and-replace on a string using a special kind of pattern called a regular expression. You can read more about regular expressions and Perl's pattern matching in the man pages that come with Perl:

  • man perlretut
  • man perlre

If you don't have these on your system, try searching Google for the same.

Applying a substitution to a variable is done with the =~ operator. So the following replaces all instances of 'foo' in the variable $var with 'bar'.

$var =~ s/foo/bar/;

All the Perl operators are documented on the 'perlop' man page.

Even though the most common separator character is a slash (hence s///), you can also use any other punctuation character as a separator. So in this case, the author has decided to use the dash (-) as the separator.

Here's the same line of code above using dash as a separator:

$var =~ s-foo-bar-;

In your case, the dash doesn't seem to add any clarity to the code, so it might be best to update it to use the conventional slashes instead.


The s/// search and replace function in perl can be used with different delimeters, which is what is done in this case. They have replaced / with the minus sign -, or dash.

The s-/-- removes the first / from the string. The s-/\Z-- matches and removes a slash at the end of the line. I think this is better written: s{/$}{}.


  1. $variable1 =~ s-/--;could be written as

    $variable =~ s{/}{}xms;
    

    or this

    $variable =~ s/ \/ //xms;
    

    It means delete the first / in the string.

  2. Regarding s-/\Z--, it is usually written like this

    $variable =~ s{/ \Z}{}xms;
    

    or this

    $variable =~ s/ \/ \Z //xms;
    

    It means delete a / if it is at the end of the string (\Z).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜