c0d34w4y has asked for the wisdom of the Perl Monks concerning the following question:

I was thinking of a code to split a given directory path
(e.g. 'foo/bar/rab/oof') and retreave all parent directories
to receive something like this: 
'foo'
'foo/bar'
'foo/bar/rab'
'foo/bar/rab/oof'

The code I came up with is as follows:
sub get_parents { my (@p, $o); for (split ("/",$_[0])) {push(@p,"$o/$_");$o.="/$_"} return \@p; }
(here's a quick test for 'perl -e' command:
perl -e '$p="foo/bar/rab/oof";for (split ("/",$p)) {push(@p,"$o/$_") +;$o.="/$_"} print join("|",@p);'
) However, is there any better/quicker way of doing the same thing? I know it does sound rather trivial... Thankx.


--
print join(" ", map { sprintf "%#02x", $_ }unpack("C*",pack("L",0x1234 +5678)))

Replies are listed 'Best First'.
Re: No other way?
by perrin (Chancellor) on Dec 13, 2001 at 03:20 UTC
    You should really use File::Spec for things like this. It's easy, the code is already written, and its cross-platform.
    File::Spec->splitdir()
(Ovid) Re: No other way?
by Ovid (Cardinal) on Dec 13, 2001 at 02:41 UTC
    $ perl -MData::Dumper -e '$p="foo/bar/rab/oof";@p=split"/",$p;@p=rever +se map{"/".join"/",@p[0..$_]}reverse(0..$#p);print Dumper @p'

    ;-)

    Cheers,
    Ovid

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

      That's a good one... ;-). Thankx! ps. I had a slight mistake in my initial code. It would 'fail' if path started with a '/'. Therefore, this should be right:
      sub get_parents { my (@p, $o); for (grep !/^$/, split ("/",$_[0])) {push(@p,"$o/$_");$o.="/$_"} return \@p; }


      --
      print join(" ", map { sprintf "%#02x", $_ }unpack("C*",pack("L",0x1234 +5678)))
        I suggest avoiding /^$/ because regexes are a lot more expensive than calling length. Thus:

        for (grep { length } split(m{/+}, $_[0])) # ...

            -- Chip Salzenberg, Free-Floating Agent of Chaos