in reply to extract month and year from localtime

My favorite quote from the Inline::C-Cookbook: "A concept is valid in Perl only if it can be shown to work in one line."

$ perl -E 'say join( ", ", sub{ 1+shift, 1900+shift }->((localtime tim +e)[4,5]) );'

This calls localtime(time) in list context, and takes a slice of the list consisting of elements #4 and #5, which are month and year. The month is zero-based, so we have to add 1. The year is 1900 based, so we have to add 1900. We do this by passing the two values into an anonymous sub that exists only for the purpose of applying some math to its inputs. We immediately dereference the sub (ie, invoke it) and return the results (still in list context). Then join the results (2 and 2014) with a comma, and print them.

Inline::C has nothing to do with the solution, of course, but somehow the quote seems appropriate. ;)


Dave

Replies are listed 'Best First'.
Re^2: extract month and year from localtime
by hdb (Monsignor) on Feb 21, 2014 at 08:30 UTC

    This kind of construct

    sub{ 1+shift, 1900+shift }->((localtime time)[4,5])

    I have been missing for a long time. Many many thanks!

      Yeah, I was kind of glad I remembered it. It seems too often we end up creating some temporary variables to receive and decorate values, when we can do our decorating inline with an immediate-use anonymous sub.


      Dave