I have a file that contains parameters using this syntax
RANGE {<value> | <value>-<value>} [ , ...]
where value
s are numbers.
for example, all these are valid syntax
RANGE 34
RANGE 45, 234
RANGE 2-99
RANGE 3-7, 15, 16, 2, 54
How can I parse the values to an array in Perl?
For example for the last example, I want my array to have 3, 4, 5, 6, 7, 15, 16, 2, 54
. The ordering of elements does not matter.
The most basic way is to check for a -
symbol to determine whether there is a range or not, parse the range using a loop and then parse the rest of the elements
my @arr;
my $fh, "<", "file.txt" or die (...);
while (<$fh>) {
if ($_ =~ /RANGE/) {
if ($_ =~ /-/) { # parse the range
< how do I parse the lower and upper limits? >
for($lower..$upper) {
$arr[++$#arr] = $_;
}
} else { # parse the first value
< how do I parse the first value? >
}
# parse the rest of the values after the comma
< how do I parse the values after the comma? >
}
}
I need help parsing the numbers. For parsing, one way I can think of is to use successive splits (on
-
,,
and). Is there some better (clean and elegant, using regex maybe?) way?
Also, comments/suggestions on the overall program structure are welcome.