Reputation: 115
i have extracted the following data in a file
0..5
8..10
12..16
but these are not working as range function. i have stored these in an array.
@arr=('0..5,8..10,12..16');
after printing the array it gives
0..5
8..10
12..16
but i need output as
0 1 2 3 4 5
8 9 10
12 13 14 15 16
am not getting where is the problem. why the stored data (..) is not working as range. function
Upvotes: 1
Views: 43
Reputation: 35198
You're starting with string representations of ranges, not actual perl ranges.
To get a perl array, you must convert your data. You could use eval
like others have recommended. However, that's like using a machete to perform a haircut.
Instead, I'd advise using more precision tools to extract the range boundaries from the string and then build your new data structure. Using split
or a regex could easily pull the values. The following does so using the latter:
use strict;
use warnings;
while (<DATA>) {
chomp;
my ($start, $end) = /(\d+)/g;
my @array = ($start .. $end);
print "@array\n";
}
__DATA__
0..5
8..10
12..16
Outputs:
0 1 2 3 4 5
8 9 10
12 13 14 15 16
The following allows for multiple ranges to be on a single row. Note, I'm using split
in this version for the sake of variety, although I could have easily used a regex as well:
use strict;
use warnings;
while (<DATA>) {
chomp;
my @array;
for my $range (split ' ') {
my ($start, $end) = split /\.{2}/, $range, 2;
push @array, ($start .. $end);
}
print "@array\n";
}
__DATA__
0..5
4..9 14..18
8..10
12..16
Outputs:
0 1 2 3 4 5
4 5 6 7 8 9 14 15 16 17 18
8 9 10
12 13 14 15 16
Upvotes: 2
Reputation: 202
Try this to store the values in the array:
@arr=((0..5),(8..10),(12..16));
Upvotes: -2
Reputation: 61510
If you want Perl to expand string ranges into Perl ranges, you must eval
that data.
use strict;
use warnings;
use feature qw(say);
my @arr=('0..5','8..10','12..16');
foreach my $range (@arr) {
say join ' ', eval ($range);
}
__END__
0 1 2 3 4 5
8 9 10
12 13 14 15 16
Upvotes: 0
Reputation: 86774
Data is data. Perl does not evaluate data as Perl (i.e. expand ..
range operator) unless you explicitly tell it to with eval
. The following debug session should clarify things for you.
$ perl -de0
Loading DB routines from perl5db.pl version 1.33
Editor support available.
Enter h or `h h' for help, or `man perldebug' for more help.
main::(-e:1): 0
DB<1> @arr = ('0..5,8..10,12..16')
DB<2> p @arr
0..5,8..10,12..16
DB<3> eval "@arr = ('0..5,8..10,12..16')"
DB<4> p @arr
0..5,8..10,12..16
DB<5> @arr = ('0..5','8..10','12..16')
DB<6> p @arr
0..58..1012..16
DB<7> @arr = eval "(0..5,8..10,12..16);"
DB<8> x @arr
0 0
1 1
2 2
3 3
4 4
5 5
6 8
7 9
8 10
9 12
10 13
11 14
12 15
13 16
DB<9>
Upvotes: 1