in reply to Re^8: Reading into array with sscanf
in thread Reading into array with sscanf
(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)@array[0..3] = ( $buffer =~ /^(\d+) (\d+) (\d+) (\d+)/ ) or die "Buffer didn't match pattern";
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.
|
|---|