in reply to Using split, splice, and join to remove time from scalar context return of localtime()
There's also strftime in POSIX.
$ perl -MPOSIX=strftime -le'print strftime "%a %b %e %Y", localtime' Thu Dec 17 2009
You could also use substr to remove the unwanted parts.
$ perl -le'substr(my $now = localtime, 11, 9, ""); print $now' Thu Dec 17 2009
Benchmark results
Rate splice strftime slice subst substr splice 93974/s -- -23% -40% -49% -64% strftime 121619/s 29% -- -23% -33% -53% slice 157894/s 68% 30% -- -14% -40% subst 182658/s 94% 50% 16% -- -30% substr 261283/s 178% 115% 65% 43% --
It surprises me that strftime is slower than slice and subst.
There's no surprise that substr is the fastest, but I don't know if it's safe. strftime is of course the safest.
Honestly, though. I don't see how the difference in speed observed could possibly matter in practice.
Benchmark code:
use strict; use warnings; use Benchmark qw( cmpthese ); use POSIX qw( strftime ); sub using_splice { my @t = split /\s/, $_[0]; splice @t, 3, 1; return join ' ', @t; } sub using_slice { return join " ", ( split " ", $_[0] )[0,1,2,4]; } my %tests = ( splice => 'my $now = using_splice(scalar(localtime));', slice => 'my $now = using_slice(scalar(localtime));', subst => '( my $now = localtime ) =~ s/(?:\d\d:){2}\d\d //;', strftime => 'my $now = strftime("%a %b %d %Y", localtime);', substr => 'substr(my $now = localtime, 11, 9, "");', ); $_ = "use strict; use warnings; $_" for values %tests; cmpthese(-3, \%tests);
Update: Added slice. Improved subst.
|
|---|