in reply to Date Handling in Perl

You may want to try localtime and sprintf:
my ($hour) = (localtime)[2]; $hour > 10 ? $_=0 : $_=60*60*24; # seconds in the day my ($mday,$mon,$year) = (localtime(time-$_))[3..5]; my $dir = sprintf('something/something/%04d/%02d/%02d',$year+1900,$mon +,$mday);
Sorry if my advice was wrong.

Replies are listed 'Best First'.
Re^2: Date Handling in Perl
by joeymac (Acolyte) on Jul 11, 2012 at 15:39 UTC

    Thanks. I have been playing with your method, but I'm not completely sure what this line is doing:

    $hour > 10 ? $_=0 : $_=60*60*24; # seconds in the day

    It seems to be some pattern matching that I am not completely familiar with. Do you mind elaborating a little? I was trying to tweak it to see if I could make it print today and/or yesterday in the final position of the directory path before I add it to my operational code, but I can only ever get it to print yesterday (/07/10).

      joeymac: That line is using the ternary conditional operator. It is essentially shorthand for an if-then-else conditional. Take a look here for more info: Conditional Operator.

      The code is better written as:

      $_ = $hour > 10 ? 0 : 60*60*24; # seconds in the day my ($mday,$mon,$year) = (localtime(time-$_))[3..5];

      Using $_ here is just laziness of not declaring a new variable. The first line returns 0 if hour <= 10, and 86400 otherwise. It is then used to modify the time() function to either get today's date (when 0) or yesterday's (when 86400).

      (I do wonder where that corruption of the ternary operator comes from. It makes no sense at all. Unless someone is teaching it as a "shorthand if"...)

      Oh, it looks like some mistake I've done, and I can't understand what's wrong (look at the Re: Date Handling in Perl - it's similar).

      I tried to use Conditional Operator to put the time (in seconds) to subtract in the $_ variable. It can be done the other way: my $subt = 0; $hour > 10 || $subt = 60*60*24; (in this case, you'll need to use $subt instead of $_)

      Sorry if my advice was wrong.

        It's the ternary operator you've botched.

        my $subst; for my $hour (5, 12) { $hour > 10 ? $subst = 0 : $subst = 86400; print $subst, "\n"; } for my $hour (5, 12) { $subst = $hour > 10 ? 0 : 86400; print $subst, "\n"; } ## output 86400 86400 86400 0