Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: How to cut the directory path?

by kevbot (Vicar)
on Feb 10, 2016 at 07:17 UTC ( [id://1154802]=note: print w/replies, xml ) Need Help??


in reply to How to cut the directory path?

There are quite a few different ways that you could perform this task. Whenever, I'm dealing with file paths I like to use Path::Tiny. For example,
#!/usr/bin/env perl use strict; use warnings; use Path::Tiny; my $filespec = "/usr/share/directory/piano_book.mp4"; my $path = path($filespec); my $rel = $path->relative("/usr/share"); print $rel, "\n"; exit;
This article is a good intro to Path::Tiny.

Replies are listed 'Best First'.
Re^2: How to cut the directory path?
by aca (Initiate) on Feb 10, 2016 at 07:20 UTC
    How it can be done using regular expression?
      If you really want to use regex, you could do this:
      my $filespec = "/usr/share/directory/piano_book.mp4"; my $relative = "." . $1 if $filespec =~ m{/usr/share(.*)};
      Or you could use split and then paste together the pieces you need.

      But you'd most probably be better off with a specialized module such as Path::Tiny mentioned above or some other.

      How it can be done using regular expression?

      You let Path::Tiny use File::Spec which uses regular expressions for you.

      I would also advise using established modules for this, but here's another regex-only way to remove the first n directories from an absolute path. It looks like you're using a *nix path, and I haven't made the effort to define a proper directory pattern in  $dir (I don't think that any character other than a  / is allowed), so you will have to fix up the  [^/] character class accordingly.

      c:\@Work\Perl\monks>perl -wMstrict -le "my $filespec = '/usr/share/directory/piano_book.mp4'; print qq{absolute: '$filespec'}; ;; my $dir = qr{ / [^/]+ }xms; # fix [^/] ;; my $n = 2; die qq{'$filespec' could not be made relative} unless $filespec =~ s{ \A (?: $dir){$n} }{.}xms; print qq{relative: '$filespec'}; " absolute: '/usr/share/directory/piano_book.mp4' relative: './directory/piano_book.mp4'
      Please see perlre, perlretut, and perlrequick.

      Update: Added error check to substitution in example code.


      Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1154802]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2024-04-25 12:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found