in reply to ignoring empty returns from split

If I understand you correctly, the following should work:
use strict; use warnings; my $line = "one====two==three"; my ( $one, $two ) = grep { length > 0 } split /=/, $line; print "$one\n$two";

Cheers,
Ovid

Update: Modified code sample to more accurately reflect poster's intention.

Update 2: tadman does raise a point about grep{length} being sufficient. I'm of the opinion that while this may be sufficient, it might not be as immediately clear to the casual observer as grep{length>0}. Any monks care to comment on the style issue?

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

Replies are listed 'Best First'.
Re^2: ignoring empty returns from split
by tadman (Prior) on Apr 24, 2001 at 01:45 UTC
    If it's not possible that length() could return a negative value, then isn't this sufficient:

         grep { length } Just curious. Not trying to be snarky.
Re: (Ovid) Re: ignoring empty returns from split
by DeusVult (Scribe) on Apr 24, 2001 at 19:38 UTC
    Ok, I tried this, but for some reason it still didn't work. I have code as follows:
    my @line = grep { length > 0 } split ( /\S+/, $_ ); print "$line[0]\t$line[1]\n";
    Where $_ will look something like this:
    STATUS mandatory
    Now, I'd assume that it would therefore print:
    STATUS mandatory
    But instead, all I get are blank lines. Can anyone think what's going wrong?

    Also, grep{length>0} is much preferable to grep{length}. The latter accomplishes absolutely nothing, fails for returns of "" so is actually somewhat buggy, and detracts from readability. The only real reason I can see to use it is a desire to show off, an impulse which should be squelched at every opportunity.

    UPDATE:Ok, I'm an idiot, but I will leave my stupidity on display for others benefit. I just noticed that I'm splitting on \S+, not \s+. So amazingly, perl did exactly what I told it to do. I just told it to do something extremely counter-productive : )

    "If you have any trouble sounding condescending, find a Unix user to show you how it's done."
    - Scott Adams

      You're splitting by \S+, this is a capital S and means anything but whitespace.
      This is probably not what you want, use a lowercase s.