How do I get the dirname of a file with Perl?

In my perl script, I have the param $FILE=/etc/sysconfig/network

in which way (in perl) I can cut only the directory and put the directory in $DIR param

in order to get:

$DIR=/etc/sysconfig

(like dirname /etc/sysconfig/network in shell script)

Answers


use File::Basename;

($name,$path,$suffix) = fileparse($fullname,@suffixlist);

$name = fileparse($fullname,@suffixlist);
$basename = basename($fullname,@suffixlist);
$dirname  = dirname($fullname);

Read more about File::Basename in perldoc.


Watch out! dirname() is deliberately dumb to emulate the dirname shell command. It is not so much "give me the directory part of this file path" as "give me all but the last part of this path". Why is that important?

my $dir = "/foo/bar/";   # obviously a directory
print dirname($dir);     # prints /foo

This is fine, just so long as you realize that dirname does not return the dirname.

If you want the above to return /foo/bar/ you're better off using File::Spec.

use File::Spec;
my($vol,$dir,$file) = File::Spec->splitpath($path);

Use the File::Basename core module:

use strict;
use warnings;
use File::Basename;

my $FILE = '/etc/sysconfig/network';
my $DIR = dirname($FILE);
print $DIR, "\n";

This prints out:

/etc/sysconfig


Need Your Help

Dynamic cell width of UICollectionView depending on label width

ios objective-c swift uicollectionview uicollectionviewcell

I have a UICollectionView, that loads cells from reusable cell, which contains label. An array provides content for that label. I can resize label width depending on content width easily with sizeT...