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.


In reply to Re: Using split, splice, and join to remove time from scalar context return of localtime() by ikegami
in thread Using split, splice, and join to remove time from scalar context return of localtime() by jffry

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.