chai6125 has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, It may seem like a stupid question. I have a variable which stores the current month
my $current_month = strftime "%m", localtime;
if my $current_month is 10 i want my previous month i want it to be 09 instead of 9.
my $previous_month = $current_month - 1;
How to acheive this.

Replies are listed 'Best First'.
Re: How to display 10 -1 =09 In Perl
by Discipulus (Canon) on Oct 30, 2014 at 08:09 UTC
    Hello you can pad with left zero using printf. See the format explication in sprintf
    perl -e "$x = 9; printf '%02s', $x " 09

    HtH
    L*
    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Re: How to display 10 -1 =09 In Perl
by LanX (Saint) on Oct 30, 2014 at 08:05 UTC
    You should only care how it's printed in the end.

    See printf and sprintf

    Cheers Rolf

    (addicted to the Perl Programming Language and ☆☆☆☆ :)

Re: How to display 10 -1 =09 In Perl
by Not_a_Number (Prior) on Oct 30, 2014 at 08:18 UTC

    But what if your current month is 1?

    Do you want your previous monnth to be 0 or 12?

      Hi My Previous month should be 12 in that case and i have taken care of that. :) I did the following can you please tell it is correct
      my $current_month = strftime "%m", localtime; my $previous_month = $current_month - 1; my $previous_month = sprintf("%02d", $previous_month);

        Last month with Time::Piece with month granularity

        #!/usr/bin/perl -- use strict; use warnings; use Time::Piece qw/ localtime /; Main( @ARGV ); exit( 0 ); sub Main { my $now = localtime; my $lastmonth = $now->prevmonth; print "$now\n$lastmonth\n"; } sub Time::Piece::prevmonth { my $t= shift; if( ! ref $t ) { $t = localtime; } my $y = $t->year; my $m = $t->mon; #~ if( $m == 12 ){ $m=1; $y++; } else { $m++; } if( $m == 1 ){ $m=12; $y--; } else { $m--; } my $nt = Time::Piece->strptime( "$y-$m", '%Y-%m' ); } __END__ Thu Oct 30 03:10:05 2014 Mon Sep 1 00:00:00 2014