简体   繁体   中英

How can I get the last two digits of a number, using Perl?

How can I get a value from particular number?

Lets say number is 20040819 . I want to get last two digit ie 19 using Perl.

my $x = 20040819;
print $x % 100, "\n";
print substr($x, -2);

Benoit's answer is on the mark and one I would use, but in order to do this with a pattern search as you suggested in your title, you would do:

my $x = 20040819;
if ($x =~ /\d*(\d{2})/)
{
    $lastTwo = $1;
}
substr("20040819", -2); 

or you can use Regexp::Common::time - Date and time regular expressions like

use strict;
use Regexp::Common qw(time);


my $str = '20040819' ;

if ($str =~ $RE{time}{YMD}{-keep})
{
  my $day = $4; # output 19

  #$1 the entire match

  #$2 the year

  #$3 the month

  #$4 the day
}

I'm just going to go beyond and show how to extract a YYYYMMDD format date into a year, month, and date:

my $str = '20040819';
my ($year, $month, $date) = $str =~ /^(\d{4})(\d{2})(\d{2})$/;

You can check for defined $year , etc., to figure out if the match worked or not.

my $num = 20040819;
my $i = 0;
if ($num =~ m/([0-9]{2})$/) {
    $i = $1;
}
print $i;

Another option:

my $x = 20040819;
$x =~ /(\d{2})\b/;
my $last_two_digits = $1;

the \\b matches a word boundary.

Solution for you:

my $number = 20040819;
my ($pick) = $number =~ m/(\d{2})$/;
print "$pick\n";

Yet another solution:

my $number = '20040819';
my @digits = split //, $number;
print join('', splice @digits, -2, 2);
$x=20040819-int(20040819/100)*100;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM