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

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

Replies are listed 'Best First'.
Re5: No other way?
by blakem (Monsignor) on Dec 13, 2001 at 08:01 UTC
    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

Re: Re: Re: Re: No other way?
by greenFox (Vicar) on Dec 13, 2001 at 22:52 UTC
    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