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.
I would suggest parsing the line into a separate variable, as
$_tends to get clobbered by other function calls. You can remove the trailing newline at the same time, withchomp.Next, you need to detect the ‘RANGE’ indicator, and extract the numbers that follow. If there is no such indicator, you can just skip to the next line:
Now, you can start extracting the numbers, splitting on the comma delimiter:
Now you can extract the dashes and translate those into ranges. This is the tricky part — if the value has a dash in it, get the first and second numbers, and turn them into a range with the
..operator; otherwise, leave the number alone:Putting all that together, and combining expressions, gives us: