ealeon
ealeon

Reputation: 12452

perl regular expression explanations

I am completely lost on this line of perl code

$path =~ s|^\./|~/|; #change the path for prettier output

I am assuming it has to do with regex. I have some understanding of regex but i just cant seem to figure this one out.

what is =~ and why is there s and how does regex expressed in perl?

Upvotes: 3

Views: 106

Answers (2)

Zach Leighton
Zach Leighton

Reputation: 1941

the =~ binds a scalar expression to a pattern match, the s is for replacement

what its doing is matching start of line with a ./ then replacing it with a ~/

as far as the | pipes, you can use any non-whitespace character to delimit parts of the regex you can use ^ or & or q or m or { whatever.. most people use / for readability but for cases where you might match on / use something else.

Hope this helps.

Upvotes: 4

choroba
choroba

Reputation: 241848

=~ is a binding operator. It applies the substitution (hence the s) to the variable $path. The substitution has two parts - a regular expression and the replacement. They are delimited by the | character in this case. The regular expression is

^\./

^ stands for the beginning of the string. \. stands for a literal dot, / stands for itself. So, ./ at the beginning of the string is replaced by ~/.

Upvotes: 6

Related Questions