in reply to Splitting up a string by lengths
The most efficient solution is:
my ($y, $m, $d) = unpack('a4a2a2', $str);
But the following solutions also work:
my $y = substr($str, 0, 4); my $m = substr($str, 4, 2); my $d = substr($str, 6, 2);
or
my ($y, $m, $d) = $str =~ /(.{4})(.{2})(.{2})/;
(Update:)
or the sillier
$str =~ /(.{4})/g; my $y = $1; $str =~ /(.{2})/g; my $m = $1; $str =~ /(.{2})/g; my $d = $1;
To convert the returned strings into numbers (which removes the leading 0s), prepend map { 0+$_ }. For example,
my ($y, $m, $d) = map { 0+$_ } unpack('a4a2a2', $str);
You can always pad with 0s later:
printf("%04d/%02d/%02d\n", $y, $m, $d);
or
$formatted = sprintf("%04d/%02d/%02d", $y, $m, $d);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Splitting up a string by lengths
by polettix (Vicar) on Jul 25, 2005 at 17:41 UTC |