Reputation: 921
what is the meaning of s#^.*/##s
because i know that in the pattern '.'
denotes that it can represent random letter except the \n
.
then '.*
'should represent the random quantity number of random letter .
but in the book it said that this would be delete all the unix type of path.
My question is that, does it means I could substitute random quantity number of random letter by space?
Upvotes: 0
Views: 350
Reputation: 69314
Please excuse a little pedantry. But I keep seeing this and I think it's important to get it right.
s#^.*/##s
is not a regular expression.
^.*
is a regular expression.
s///
is the substitution operator.
The substitution operator takes two arguments. The first is a regular expression. The second is a replacement string.
The substitution operator (like many other quote-like operators in Perl) allows you you change the delimiter character that you use.
So s###
is also a substitution operator (just using #
instead of /
).
s#^.*/##
means "find the text that matches the regular expression ^.*/
and replace it with an empty string. And the s
on the end is a option which changes the regex so that the .
matches "\n" as well as all other characters.
Upvotes: 0
Reputation: 263507
Substitutions conventionally use the /
character as a delimiter (s/this/that/
), but you can use other punctuation characters if it's more convenient. In this case, #
is used because the regexp itself contains a /
character; if /
were used as the delimiter, any /
in the pattern would have to be escaped as \/
. (#
is not the character I would have chosen, but it's perfectly valid.)
^
matches the beginning of the string (or line; see below)
.*/
matches any sequence of characters up to and including a /
character. Since *
is greedy, it will match all characters up to an including the last /
character; any precedng /
characters are "eaten" by the .*
. (The final /
is not, because if .*
matched all /
characters the final /
would fail to match.)
The trailing s
modifier treats the string as a single line, i.e., causes .
to match any character including a newline. See the m
and s
modifiers in perldoc perlre
for more information.
So this:
s#^.*/##s
replaces everything from the beginning of the string ($_
in this case, since that's the default) up to the last /
character by nothing.
If there are no /
characters in $_
, the match fails and the substitution does nothing.
This might be used to replace all directory components of an absolute or relative path name, for example changing /home/username/dir/file.txt
to file.txt
.
Upvotes: 4
Reputation: 89584
s -> subsitution # -> pattern delimiter ^.* -> all chars 0 or more times from the begining / -> literal / ## -> replace by nothing (2 delimiters) s -> single line mode ( the dot can match newline)
Upvotes: 5
Reputation: 91498
It will delete all characters, including line breaks because of the s
modifier, in a string until the last slash included.
Upvotes: 3