Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: localtime parse within hash init

by roboticus (Chancellor)
on Nov 04, 2014 at 11:33 UTC ( #1106014=note: print w/replies, xml ) Need Help??


in reply to localtime parse within hash init

NetWallah:

It may not be particularly elegent, but I'd just create a sub that returns the hash.

sub date_hash { my ($dtm, $rv) = (shift // time, {}); @{$r}{qw(sec min hour mday mon year wday yday isdst)} = localtime( +$dtm); return $rv; }

My reasons are:

  • This gives you the opportunity to give it a name that makes your initializer easy to read:
    my %stuff=(otherinfo=>"this and that", dateinfo=>{%{date_hash($aTime)}});
  • I find that when I need something like this in a program, it may start out being needed only once, but frequently gets used a few more times.
  • It moves an ugly bit of code out of the way, usually into a projFooUtils.pm file, which often has a handful of routines simple enough to never have to look at again.

Update: On the way in to work, I remembered that I *have* a similar function in my MCMUtils.pm package already, with a couple of changes:

  • I can never remember the exact abbreviations to use for the date/time chunks, so I use my 'standard' values: YYYY, YY, MM, DD, hh, mm, ss, dow
  • I go ahead and "fix" the month (+1) and year values (YYYY={year}+1970, YY=({year}+1970)%100).
  • I let the user send in the keys desired. So if they send in YYYY, MM, DD that's all I'll return. But if no keys are sent in, it returns all of 'em. Yeah, it makes it a little overcomplicated, perhaps, but I use it in a good few places.

I'll try to remember to update this node with the code for that function when I get back home. (It's not in my $work util packages (yet)).

...roboticus

When your only tool is a hammer, all problems look like your thumb.

Replies are listed 'Best First'.
Re^2: localtime parse within hash init
by NetWallah (Canon) on Nov 04, 2014 at 15:53 UTC
    thanks roboticus (++).

    That leads to:

    perl -E 'my %stuff=(otherinfo=>"this and that", dateinfo=> sub{ my %r; @r{qw|sec min hour mday mon year wday yday isdst|} =localtime(time); return \%r}->()); say "sec=",$stuff{dateinfo}{sec}, " year=",$stuff{dateinfo}{year}'
    Which works, is pretty decent, and free of external modules.

            "You're only given one little spark of madness. You mustn't lose it."         - Robin Williams

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1106014]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2022-08-10 18:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?