in reply to split string by character count
pack and unpack are very suited for fixed-length strings. As your list of elements is variable, you will have to create the template for unpack dynamically from your list. The idea is first to split up your list of elements into the template and the names, and then to use these two to create the hash from that:
my $unpack_template; my @names; for (@list) { die "Don't know what to do with $_" unless /^\d+: ([-a-z]+) (\d+)$/; $unpack_template .= "A$2"; push @name, $1; }; print "I will be unpacking using '$unpack_template'\n"; my @values = unpack $unpack_template, $string; # Now, pack everything into a nice hash so we can use the name # to address the value: my %result; @result{ @name } = @values; for my $k (sort keys %result) { print "$k => $result{$k}\n"; };
|
|---|