As documented, the default for the first argument of split is ' '. ("As a special case, specifying a PATTERN of space (' ') will split on white space just as split with no arguments does.")

$ perl -MData::Dumper -e' $_=" 56 1752.eps a b"; print Dumper split; ' $VAR1 = '56'; $VAR2 = '1752.eps'; $VAR3 = 'a'; $VAR4 = 'b'; $ perl -MData::Dumper -e' $_=" 56 1752.eps a b"; print Dumper split " "; ' $VAR1 = '56'; $VAR2 = '1752.eps'; $VAR3 = 'a'; $VAR4 = 'b';

The next problem is that "2" is wrong for the third argument. You'd want to use "3" and ignore the last value returned.

$ perl -MData::Dumper -e' $_=" 56 1752.eps a b"; print Dumper split " ", $_, 2; ' $VAR1 = '56'; $VAR2 = '1752.eps a b'; $ perl -MData::Dumper -e' $_=" 56 1752.eps a b"; print Dumper split " ", $_, 3; ' $VAR1 = '56'; $VAR2 = '1752.eps'; $VAR3 = 'a b';

Solutions:

for (@data) { my @a = (split)[0,1]; my @a = (split " ", $_, 3)[0,1]; my ($x, $y) = split(" ", $_, 3); my ($x, $y) = split; ... }

split is optimised so that it doesn't do any unnecessary work for the last one. You could also avoid split entirely.

my ($x, $y) = /^\s*(\S+)\s+(\S+)/;

In reply to Re: Split(), Initial Spaces, & a limit? by ikegami
in thread Split(), Initial Spaces, & a limit? by cmv

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.