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

I have been assigned to maintain someone else's perl code. I am having trouble with one line of it:
$fname =~ s!.*/!!;
I cannot find information from my available perl books and online resurces to figure out what is going on here. May I have some help from someone? Thanks in advance.

Replies are listed 'Best First'.
Re: Binding Question
by dreadpiratepeter (Priest) on Jul 24, 2002 at 14:27 UTC
    Simple. The exclamation points are the delimiters for the expression (to avoid having to backslash the forward slash). The expression says: remove everything up to the last '/' from the expression including the '/'.
    Remember that the '*' modifier is greedy and will suck up all the '/'s in the expression. To get rid of everything up to the first slash you can use the *? modifier, which does a non-greedy match

    -pete
    "Pain heals. Chicks dig scars. Glory lasts forever."
Re: Binding Question
by kodo (Hermit) on Jul 24, 2002 at 14:29 UTC
    It will cut anything but the stuff after the last "/" in $fname.

    Example:
    $fname = 'lalalla/home'; $fname =~ s!.*/!!; print $fname;
    $fname will be 'home';

    Maybe you got confused because ! is used as delimiter here, have a look at Japhy's excellent perl-regexpr-book to learn how it really works.

    giant
Re: Binding Question
by mkmcconn (Chaplain) on Jul 24, 2002 at 14:49 UTC

    That's an icky and unreliable way to get the filename from a path (my repentance for using it in the past is showing).

    File::Basename, File::Spec and URI::file are more portable.

    But, for another quicky that may or may not be more legible (it's a common idiom), this will also work for *nix and MS paths:

    my ($fname) = $fullpath =~ m/([^\\|\/]+)$/;

    mkmcconn
    update: modified my tone and added a module

Re: Binding Question
by broquaint (Abbot) on Jul 24, 2002 at 14:29 UTC
    That is substituting everything up to the last '/' in $fname with nothing, which is essentially the same as
    substr($fname, 0, rindex($fname, '/') + 1) = '';
    For more information on substituting in perl see the s/// manpage and for info on regular expressions in perl see the perlre manpage.
    HTH

    _________
    broquaint

Re: Binding Question
by vek (Prior) on Jul 24, 2002 at 18:40 UTC
    You'll also find something very similar in the Perl Cookbook on page 164:
    # strip to basename ($progname = $0) =~ s!^.*/!!;
    -- vek --