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

I am splitting some lines from an input line using the standard
@flds = split(/\s+/);
However, I have discovered that some lines may start with whitespace, meaning sometimes I get 4 elements in @flds, and sometimes 5, in which case the first element of @flds is empty. This screws up the code I have later that depends on certain values being in certain places in @flds. Is there a pattern I can use that would discard this first empty field? Or must I, for instance, test for this emptiness and shift it away?

Replies are listed 'Best First'.
Re: A regexp/split question
by swiftone (Curate) on Jun 08, 2000 at 00:39 UTC
    Leave out the /\s+/. As per the perlfunc:split, (found in perlman:perlfunc)this will skip leading whitespace.
    @flds=split;
    <code> If EXPR is omitted, splits the `$_' string. If PATTERN is also omitted, splits on whitespace (after skipping any leading whitespace). Anything matching PATTERN is taken to be a delimiter separating the fields. (Note that the delimiter may be longer than one character.) <code>
Re: A regexp/split question
by takshaka (Friar) on Jun 08, 2000 at 00:41 UTC
    @flds = split; # or @flds = split ' ';
    Skips leading whitespace.
Re: A regexp/split question
by ivey (Beadle) on Jun 08, 2000 at 00:39 UTC
Re: A regexp/split question
by mdillon (Priest) on Jun 08, 2000 at 00:37 UTC
    i would do this: @flds = grep { length } split(/\s+/);
A regexp/split question
by young_yang (Acolyte) on Jun 08, 2000 at 06:20 UTC
    wrote by Monk takshaka on Wed Jun 7 2000 at 20:41 @flds = split; # or @flds = split ' '; Skips leading whitespace. ########################## I can't understand these expression,but It worked indeed,why? @flds=split ' ' equate @flds=split(' ',$_); it is not equate @flds=split(/ /,$_); What different between ' ' and / / ? I hope you can understand my poorly english,Thanks!
      split; and split ' ', $line; are special cases that split on whitespace just like /\s+/ but without leading null fields.

      This behavior is described in the perlfunc entry on split.

RE: A regexp/split question
by Corion (Patriarch) on Jun 08, 2000 at 11:42 UTC

    There are many ways to do what you want. The easiest (IMO) is to later fix the array. You could also (which seems more elegant to me) preprocess the line just before splitting, by removing all offending whitespace :

    s/^\s+//g;