tags:

views:

135

answers:

7

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.

+8  A: 
my $x = 20040819;
print $x % 100, "\n";
print substr($x, -2);
Benoit
The `%` option is the most natural in my opinion.
Nathan Fellman
I find the substr more explicit.
Daenyth
I'd go with the substr.
brian d foy
I would also go with the `substr` command, personally.
Platinum Azure
+2  A: 

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;
}
RC
A: 

Another option:

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

the \b matches a word boundary.

Nathan Fellman
Have you heard about Unicode? `\d` matches more than just ASCII digits (`[0-9]`): indian digits and others...
dolmen
Maybe we'll get the /a flag in Perl 5.14 though :)
brian d foy
+2  A: 
my $num = 20040819;
my $i = 0;
if ($num =~ m/([0-9]{2})$/) {
    $i = $1;
}
print $i;
Ruel
A: 

Yet another solution:

my $number = '20040819';
my @digits = split //, $number;
print join('', splice @digits, -2, 2);
Alan Haggai Alavi
This soluting gives an list containing two one-character strings: `('1', '9')`.
dolmen
Fixed using `join`, though I wonder if he meant to use `substr`?
Platinum Azure
+2  A: 
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
}
Nikhil Jain
+1  A: 

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.

Platinum Azure