Whenever you find yourself numbering individual variables instead of giving them names, you should recognise that what you ought to be using is an array.
It does away with the need for eval and it is automatically extensible.
A second thing I notice in your code is that your use of substr is wrong. The 3rd parameter to substr is the number of bytes, not the end position of the substring. As you have shown it, your variables will get larger and larger in length:
$d1 = substr($field, 0, 2); # 2 bytes
$d2 = substr($field, 2, 2+2); # 4 bytes
$d3 = substr($field, 4, 4+6); # 6 bytes etc.
You also show $i+=$n in the loop increment, $i-1/$n to generate your varnames, but a fixed value of 2 in the substr?
There are several ways to do what you want without using eval or symbolic refs.
my @d;
for my $i (0 .. $length-$n) {
$d[$i] = substr($field, $i*$n, $n)
}
Or my @d = map{ substr $field, $_*n, $n } 0 .. ($length)/$n;
Or my @d = unpack("A$n " x $length/$n, $field);
Or probably the simplest my @d = $field =~ m[.{1,$n}]g;
Examine what is said, not who speaks.
1) When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong.
2) The only way of discovering the limits of the possible is to venture a little way past them into the impossible
3) Any sufficiently advanced technology is indistinguishable from magic.
Arthur C. Clarke.
|