in reply to (Ovid) Re: No other way?
in thread No other way?

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)))

Replies are listed 'Best First'.
Re: Re: Re: No other way?
by chip (Curate) on Dec 13, 2001 at 03:57 UTC
    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';

        Well, in order to do a substitution you might have to assign to a new variable so as not to modify the original value, and that could be a worse readability hit than the grep; depends on the context.

        PS: I think you meant s#^/+##, what with the possibility of multiple leading slashes.

            -- Chip Salzenberg, Free-Floating Agent of Chaos