in reply to localtime parse within hash init
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 |
In Section
Seekers of Perl Wisdom