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;
In reply to Re: One liner: split fixed-width field into equal length chunks...
by BrowserUk
in thread One liner: split fixed-width field into equal length chunks...
by mr. jaggers
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |