user954299
user954299

Reputation: 195

How to extract directory names from a path in Perl

I have a path like this

/home/user/doc/loc

I want to extract home, user, doc, loc separately. I tried split (////) and also split("/") but none of them worked. Please give me sample script:

while (<EXPORT>) {
if (/^di/) { 
    ($key, $curdir) = split(/\t/); 
    printf "the current dir is %s\n", $curdir;
    printf("---------------------------------\n");
    ($home_dir, $user_dir, $doc_dir, $loc_dir) = split("/");    
  }
 }

But it didn't work; hence please help me.

Upvotes: 1

Views: 6337

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 754820

Given $curdir containing a path, you'd probably use:

my(@names) = split m%/%, $curdir;

on a Unix-ish system. Or you would use File::Spec and splitdir. For example:

#!/usr/bin/env perl
use strict;
use warnings;
use File::Spec;

my $curdir = "/home/user/doc/loc";
my(@names) = split m%/%, $curdir;

foreach my $part (@names)
{
    print "$part\n";
}

print "File::Spec->splitdir()\n";
my(@dirs) = File::Spec->splitdir($curdir);

foreach my $part (@dirs)
{
    print "$part\n";
}

Ouput (includes a leading blank line):

 
home
user
doc
loc
File::Spec->splitdir()
 
home
user
doc
loc

Upvotes: 6

FoolishSeth
FoolishSeth

Reputation: 4031

split's first result will be the string preceding the first instance of the regular expression passed to it. Since you have a leading "/" here you would get an empty string in $home_dir, 'user' in $user_dir and so on. Add undef to the list assignment's first position or alternatively trim a leading slash first.

Also I'm not sure if you can call split without passing it $curdir here. Try:

(undef, $home_dir, $user_dir, $doc_dir, $loc_dir) = split("/", $curdir);

Upvotes: 0

Related Questions