Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

how to remove everything before last slash in perl?

by mipatel (Novice)
on Jun 23, 2012 at 19:46 UTC ( #978008=perlquestion: print w/replies, xml ) Need Help??
mipatel has asked for the wisdom of the Perl Monks concerning the following question:

i have a script that generates the output with the fullpath of the directory.

Example y:/home/lib/directory/book y:/home/lib/directory/book_manager y:/home/lib/directory/piano_book
i want the output as
book book_manager piano book
is there any regex for this guys? i tried doing this but it still leaves the slash at the end $output =~ s{.*(/)}{$1};

Replies are listed 'Best First'.
Re: how to remove everything before last slash in perl?
by roboticus (Chancellor) on Jun 23, 2012 at 19:52 UTC


    It sounds like File::Basename might be a good fit for you. But if you *really* want to use a regex, you could do something like s#^.*/##.


    When your only tool is a hammer, all problems look like your thumb.

      hey thanks for your answer. It worked. now i dont even have the last slash :)

        The fact that you began with this…


        …and ended up with this…


        …makes me suspicious that you both started and ended by using someone else's regular expression pattern, and that you understand neither one.

        My advice: Avoid copy and paste programming. Sometimes, it's better to figure out how to do something yourself than it is to ask someone else how to do it. You learn more this way.

Re: how to remove everything before last slash in perl?
by muba (Priest) on Jun 23, 2012 at 20:08 UTC

    Another approach, if you really want to use a regex, would be to capture just that part that you're interested in:

    my $somestring = "y:/home/lib/directory/piano_book"; ($somestring) = $somestring =~ m#([^/]+)$#; print $somestring; __END__ piano_book

    Update: or just to show that always TIMTOWTDI:

    my $somestring = "y:/home/lib/directory/piano_book"; my $idx = rindex($somestring, "/"); $somestring = substr($somestring, $idx+1); print $somestring;

      More than one way?

      my $filename = (split m{/} => $full_path)[-1];

      I agree however that File::Basename is way better, as it also deals with filesystems other than Unix-like that use a forward slash.

      Enjoy, Have FUN! H.Merijn
Re: how to remove everything before last slash in perl?
by 7stud (Deacon) on Jun 23, 2012 at 21:32 UTC

    Your regex:

    $output =~ s{.*(/)}{$1}

    ...says to match any number of characters followed by a slash, then replace the whole match with a slash. As a result, if there is a match there is going to be a slash in the output. There's actually no point in even specifying $1 because your substitution is the same as:


    Here are some other solutions:


    use strict; use warnings; use 5.010; use File::Basename; my @paths = ( "y:/home/lib/directory/book", "y:/home/lib/directory/book_manager", "y:/home/lib/directory/piano_book", ); my @results = map basename($_), @paths; say "@results"; --output:-- book book_manager piano_book


    @results = map { (split '/', $_)[-1] } @paths;

Re: how to remove everything before last slash in perl?
by kcott (Chancellor) on Jun 24, 2012 at 12:53 UTC

    Another option you have is the built-in module File::Spec.

    Here's a script that shows how you might use it. Things to note (details in the doco):

    • $no_file - Set to a TRUE value, indicates these are paths to directories.
    • grep { length } ... - Handles "... empty directory names ('') can be returned ...".
    • with_trailing_slash - Extra test to show how trailing slashes are handled.
    #!/usr/bin/env perl use 5.010; use strict; use warnings; use File::Spec; my $no_file = 1; while (my $path = <DATA>) { chomp $path; my ($volume, $directories, $file) = File::Spec->splitpath($path, $no_file); my @dirs = grep { length } File::Spec->splitdir($directories); my $last_dir = $dirs[-1]; say qq{$path }, q{.} x (24 - length($last_dir) - $path =~ m{\W$}), qq{ $last_dir}; } __DATA__ y:/home/lib/directory/book y:/home/lib/directory/book_manager y:/home/lib/directory/piano_book y:/home/lib/directory/with_trailing_slash/


    $ y:/home/lib/directory/book .................... book y:/home/lib/directory/book_manager ............ book_manager y:/home/lib/directory/piano_book .............. piano_book y:/home/lib/directory/with_trailing_slash/ .... with_trailing_slash

    -- Ken

Re: how to remove everything before last slash in perl?
by Anonymous Monk on Jun 24, 2012 at 04:08 UTC
    #!/usr/bin/perl -- use strict; use warnings; use Path::Class; @ARGV or @ARGV = ( qw' y:/home/lib/directory/book y:/home/lib/directory/book_manager y:/home/lib/directory/piano_book ' ); print file($_)->basename,"\n" for @ARGV; __END__ __END__ book book_manager piano_book

      dir have basename too

      $ perl -MPath::Class -le " print dir($_)->basename for @ARGV" ro/sham/ +bo ono/mato/poeia otorhinolaryngology bo poeia otorhinolaryngology

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://978008]
Approved by muba
Front-paged by cavac
[Discipulus]: choroba i'm considering to add some connection checking to your CB tk program: something like..
[Discipulus]: i got also a parser error, but once
[KurtZ]: Code Tags
[KurtZ]: ?
[choroba]: <code>...</code>
[choroba]: Discipulus: Yes, all get calls should be wrapped in a Try::Tiny
[choroba]: you can just create a ticket :)

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (9)
As of 2017-07-24 09:22 GMT
Find Nodes?
    Voting Booth?
    I came, I saw, I ...

    Results (348 votes). Check out past polls.