Another perl-minded way to do your scanf function would be
@array[0..3] = ( $buffer =~ /^(\d+) (\d+) (\d+) (\d+)/ ) or die "Buffer didn't match pattern";
(In list context, the regex match returns a list of the captures, which you can assign to something. If it fails to match, it returns an empty list. Putting the result of the assignment into scalar context converts to the count of list elements, which is nonzero if it matched and zero if it didn't, giving you a boolean to branch off of)

Using the regex engine might seem like overkill for this simple case, but in most real-world problems the input has some obstacles you want to work around, and using regular expressions is way easier than dancing around with byte offsets and substr and sscanf.

For even more advanced parsing, checkout the "\G" and "/gc" features of the regex engine, which allow you to iterate along a string without needing to split out substrings, avoiding copying the data over and over into new variables.


In reply to Re^9: Reading into array with sscanf by NERDVANA
in thread Reading into array with sscanf by colintu

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.