I need to read a line of numbers separated by spaces and ending with a 0, like this:
1 2 3 4 7 20 12334 0Each number needs to only be processed individually, so I don't have to keep them all in memory. The problem is, input lines can be very long and reading them with <> and splitting consumes a lot of memory.
I tried setting a space as the input record separator, but it doesn't get the last number correctly.
use strict; use warnings; sub do_something { print '{', $_[0], "}\n" } local $/ = ' '; while (<>) { do_something($_); }
I also tried to simulate C++ cin behaviour with the following function:
sub cin_read { my $inchar = getc; $inchar = getc while $inchar =~ /^\s$/; my $result = ''; while ($inchar =~ /^\S$/) { $result .= $inchar; $inchar = getc; } return $result; }
However, it's overly complicated and slow.
How else could I go about doing this?
EDIT: Updated sample input to include multi-digit numbersIn reply to Reading a huge input line in parts by kroach
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |