spaceship has asked for the wisdom of the Perl Monks concerning the following question:

I have been editing a piece of code and came across the following line which stores the name of the curent perl script.
my $this_proc = $0 =~ /^.+\/(.+)$/ ? $1 : $0;
I do not understand how and what does the ~ do as it just seems to remove the ./ off the front off the script name.

Thanks in advance

Janitored by Arunbear - added code tags, as per Monastery guidelines

Replies are listed 'Best First'.
Re: Regular expression problemette
by eibwen (Friar) on Apr 21, 2005 at 00:14 UTC
    Basically the code provides the same functionality as the unix command basename. The code detects whether the invocation contained any path elements (eg $ ./code.pl or $ /home/user/code.pl) and returns the actual filename.

    $this_proc = $0 # Filename of code (as invoked) =~ # "Perform" Regular Expression /^.+\/ # Matches everything until the last / (.+)$/ # Capture filename (in $1) ? # If Regex was successful $1 # Return the filename : # Otherwise (Else) $0; # Return the filename as invoked

Re: Regular expression problemette
by tlm (Prior) on Apr 20, 2005 at 23:09 UTC

    $this_proc = $0 =~ /^.+\/(.+)$/ ? $1 : $0;
    The ~ is part of =~ operator; it tells perl to match the LHS against the regular expression on the RHS.

    the lowliest monk

Re: Regular expression problemette
by bart (Canon) on Apr 21, 2005 at 00:44 UTC
    ALternatively, try
    (my $this_proc = $0) =~ s:^.*/::;
    This first copies the old value of $0, the name of the current script (see perlvar), into $this_proc, and then modifies that, deleting everything up to and including the last slash.

    BTW Your snippet will fail for filenames like "/foo.pl". To fix it, replace the first plus with a star:

    $this_proc = $0 =~ /^.*\/(.+)$/ ? $1 : $0;
Re: Regular expression problemette
by friedo (Prior) on Apr 21, 2005 at 00:05 UTC
    The =~ operator binds a variable to a regexp. In this example, the regexp is looking at $0 to see if it begins with a path. If it does, the filename by itself is captures to $1. This is combined with a ternary conditional (?:). If the regexp is successful, the match is returned to $this_proc, otherwise, $0 is.
Re: Regular expression problemette
by phaylon (Curate) on Apr 21, 2005 at 00:51 UTC
    Well, if you're going through that code, maybe you like to take a look at FindBin.

    Ordinary morality is for ordinary people. -- Aleister Crowley
Re: Regular expression problemette
by spaceship (Initiate) on Apr 21, 2005 at 07:23 UTC
    Thank you all for your help. I am slowly beginning to understand the old regexps. Much appreciated