in reply to No other way?

$ 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.

Replies are listed 'Best First'.
Re: (Ovid) Re: No other way?
by c0d34w4y (Acolyte) on Dec 13, 2001 at 02:51 UTC
    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

        Another reason to avoid /^$/ is that it non-intuitively matches a single newline:
        #!/usr/bin/perl -wT use strict; # only one one of these is an "empty" string right? my @arr = ("", "\n", "dog", "cat"); my @haslength = grep {length} @arr; my @notempty = grep {!/^$/} @arr; print scalar @haslength, " members have length\n"; print scalar @notempty, " members are not \"empty\"\n"; __END__ =head1 OUTPUT 3 members have length 2 members are not "empty"
        So, /^$/ actually classifies a single newline as an "empty" string.... Sometimes thats what you want, but it isn't usually what people expect.

        -Blake

        given that the grep for /^$/ was to skip the null first field returned by split (because the first character in the string was the delimiter "/"), wouldn't it be "better" (more readable) to just explicitly remove it- ie
        s#^/##; # remove the leading delimiter

        The code as written silently munches all null fields which is fine because we don't expect a directory called null (ie in /foo/bar//rab/oof) but if the idiom is transported to another set of data...

        split /' '/ nicely removes any leading white space... it could be handy to have an option to do this for other delimiters.

        --
        my $chainsaw = 'Perl';