This is assuming all your widths are the same, otherwise you would want to either pass the required width as an argument to the sub (not a good idea if you use the size in multiple places) or create a hash with values and there corresponding lengths and pass the item_name. I think this would give it a little more durability. Some thing like this:$c = "test test test"; $c = correct_length($c); $fmt = "A4 x1 A4 x1 A4 x1 A4"; @c = unpack($fmt, "$c"); print join ("*",@c), "\n"; $d = "test test test "; $d = correct_length($d); $fmt = "A4 x1 A4 x1 A4 x1 A4"; @d = unpack($fmt, "$d"); print join ("*",@d), "\n"; sub correct_length { my ($string) = shift; $string .= ' ' unless length($string) >= 15; return($string); }
Then the subroutine above could be passed the item_name and the string so the only place you would have to modify length would be in the formats hash, but I don't know if your data is that complex/varied.my %formats = ( "item_name" => 15, # where 15 is the length "item_name2" => 20, # etc. ); # code removed for demonstration $c = correct_length($c,'item_name'); sub correct_length { my ($string,$item) = @_; $string .= ' ' unless length($string) >= $formats{$item}; return($string); }
In reply to Re: Unpack/format
by trs80
in thread Unpack/format
by Reverend Phil
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |