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

Brethren,
Is it possible to use sprintf to return the last 2 digits of a 4 digits string?
I can do it with a regex, such as,
my $year = 2002; $year =~ s/.*(\d\d)$/$1/; print $year;
which returns 02, but I'd rather not use a regex (for speed reasons).
Note: the variable will always contain a 4 digit number.
I've checked the sprintf docs, but can't figure out from it how to do this.
(of course, any other non-regex solution would be welcome!

Thanks.

Replies are listed 'Best First'.
Re: sprintf the last 2 digits
by BrowserUk (Patriarch) on Oct 03, 2002 at 13:54 UTC

    Try

    my $year = 2002; $year =substr($year, -2); print $year;

    Cor! Like yer ring! ... HALO dammit! ... 'Ave it yer way! Hal-lo, Mister la-de-da. ... Like yer ring!
      BroswerUK ++ !
      Kudos for figuring out what I was really looking for!
      This is what happens when I go to bed at 4am, rather than my usual midnight-ish! ;)
Re: sprintf the last 2 digits
by Zaxo (Archbishop) on Oct 03, 2002 at 14:08 UTC

    Timtowdi, this makes sure it's an integer, but you still need sprintf to get the leading zero:

    printf '%02d', $year %= 100;

    After Compline,
    Zaxo

Re: sprintf the last 2 digits
by diotalevi (Canon) on Oct 03, 2002 at 14:04 UTC

    I liked BrowserUK's answer better but your regex is needlessly wastful. This just plucks the last two characters from the line if they are digits.

    my $year = 2002; ($year) = $year =~ m/\d\d$/g;

    __SIG__
    printf "You are here %08x\n", unpack "L!", unpack "P4", pack "L!", B::svref_2object(sub{})->OUTSIDE

Re: sprintf the last 2 digits
by belg4mit (Prior) on Oct 03, 2002 at 18:06 UTC
    UPDATE: Doh! How did Zaxo sneak that in with a timestamp 4 hours before mine just as a I replied? ;-)

    Year modulo one hundred would also work.

    printf("%02", $year % 100);

    --
    perl -wpe "s/\b;([mnst])/'$1/g"

Re: sprintf the last 2 digits
by hopes (Friar) on Oct 03, 2002 at 16:07 UTC
    Just another way to do it:
    perl -le '$_=shift;print((split//)[-2,-1])' 2003 perl -le 'print((split//,shift)[-2,-1])' 2003

    Hopes
    perl -le '$_=$,=q,\,@4O,,s,^$,$\,,s,s,^,b9,s,$_^=q,$\^-]!,,print'