user363638
user363638

Reputation: 101

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 i.e 19 using Perl.

Upvotes: 3

Views: 10499

Answers (9)

rodee
rodee

Reputation: 3171

$x=20040819-int(20040819/100)*100;

Upvotes: -1

user2899446
user2899446

Reputation: 3

Solution for you:

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

Upvotes: 0

Nikhil Jain
Nikhil Jain

Reputation: 8352

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
}

Upvotes: 3

Platinum Azure
Platinum Azure

Reputation: 46193

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.

Upvotes: 3

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74252

Yet another solution:

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

Upvotes: 0

Ruel
Ruel

Reputation: 15780

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

Upvotes: 2

Nathan Fellman
Nathan Fellman

Reputation: 127538

Another option:

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

the \b matches a word boundary.

Upvotes: 1

RC.
RC.

Reputation: 28257

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;
}

Upvotes: 4

Benoit
Benoit

Reputation: 79205

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

Upvotes: 12

Related Questions