Reputation: 141
I want to know the meaning of
"$0 =~ s!.*/!!"
in perl , and how can I learn this grammer ? Welcome all kinds of answers.
Upvotes: 2
Views: 1256
Reputation: 189357
This truncates the name of the script ($0
) to just its basename. It is useful for diagnostics. Without the truncation, your warning messages
warn "$0: Failed to mumble"
would come out as
weird/long/path/to/mumble.pl: Failed to mumble at line 3.
whereas with the truncation, it shows
mumble.pl: Failed to mumble at line 3.
So it's just a readability tweak for warning messages, really. But it's a common idiom.
The hard part for a beginner is probably the realization that s!foo!bar!
is just another way to say s/foo/bar/
. This is a godsend when you need to perform substitutions on strings which contain slashes. Without this syntactic sugar, you would need to backslash the slashes s/.*\///
which for a single slash isn't too ghastly, but it quickly leads to leaning toothpicks.
Upvotes: 9