Reputation: 101
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
Reputation: 3
Solution for you:
my $number = 20040819;
my ($pick) = $number =~ m/(\d{2})$/;
print "$pick\n";
Upvotes: 0
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
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
Reputation: 74252
Yet another solution:
my $number = '20040819';
my @digits = split //, $number;
print join('', splice @digits, -2, 2);
Upvotes: 0
Reputation: 15780
my $num = 20040819;
my $i = 0;
if ($num =~ m/([0-9]{2})$/) {
$i = $1;
}
print $i;
Upvotes: 2
Reputation: 127538
Another option:
my $x = 20040819;
$x =~ /(\d{2})\b/;
my $last_two_digits = $1;
the \b
matches a word boundary.
Upvotes: 1
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