in reply to modify the contents of an array
It appears blazar has the best approach. I added data validation to, and bencmarked, the two main solutions (regexes and unpack), as well as doing the same thing with sprintf (just for fun).
@my_array = <DATA>; use Benchmark ':all'; sub regex_method { my $array = [@_]; for (@$array) { next unless /^\d{6}\s*$/; ## validate data s:(\d{2})(?!$):$1/:g; } } sub sprint_method { my $array = [@_]; for (@$array) { next unless /^\d{6}\s*$/; ## validate data $_ = sprintf "%d%d/%d%d/%d%d", split('',$_); } } sub unpack_method { my $array = [@_]; for (@$array) { next unless /^\d{6}\s*$/; ## validate data $_=join '/', unpack 'A2' x 3, $_ for @arr; } } cmpthese( 50000, { 'regex' => sub { regex_method(@my_array) }, 'sprintf' => sub { sprint_method(@my_array) }, 'unpack' => sub { unpack_method(@my_array) }, }); __DATA__ 010203 020304 012398 122399
With these results (representative of many runs):
Rate sprintf regex unpack sprintf 20383/s -- -23% -79% regex 26441/s 30% -- -73% unpack 96899/s 375% 266% --
|
|---|