Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract a filename from a path using Perl?

I have a Perl variable I populate from the database. Its name is $path. I need to get another variable $file which has just the filename from the pathname.

I tried:

$file = $path =~ s/.*\///;

I am very new to Perl.

like image 902
JUAN Avatar asked Jan 22 '11 11:01

JUAN


2 Answers

Why reinvent the wheel? Use the File::Basename module:

use File::Basename;
...
$file = basename($path);

Why did $file=$path=~s/.*\///; not work?

=~ has higher precedence than =

So

$file = $path =~s/.*\///;

is treated as:

$file = ($path =~s/.*\///);

which does the replacement in $path and assigns either 1 (if replacement occurs) or '' (if no replacement occurs).

What you want is:

($file = $path) =~s/.*\///;

which assigns the value of $path to $file and then does the replacement in $path.

But again there are many problems with this solution:

  1. It is incorrect. A filename in Unix based systems (not sure about Windows) can contain newline. But . by default does not match a newline. So you'll have to use a s modifier so that . matches newline as well:

    ($file = $path) =~s/.*\///s;
    
  2. Most importantly it is not portable as it is assuming / is the path separator which is not the case with some platforms like Windows (which uses \), Mac (which uses :). So use the module and let it handle all these issues for you.

like image 90
codaddict Avatar answered Oct 07 '22 20:10

codaddict


use File::Basename 

Check the below link for a detailed description on how it works:

http://p3rl.org/File::Basename

like image 44
lukuluku Avatar answered Oct 07 '22 20:10

lukuluku