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