Perl Regex Variable Replacement printing 1 instead of desired extraction

97 views Asked by At

Case 1:

year$ = ($whole =~ /\d{4}/);
print ("The year is $year for now!";)

Output: The year is The year is 1 for now!

Case 2:

$whole="The year is 2020 for now!";
$whole =~ /\d{4}/;
$year =  ($whole);
print ("The year is $year for now!";)

Output: The year is The year is 2020 for now! for now!

Is there anyway to make the $year variable just 2020?

3

There are 3 answers

0
Timur Shtatland On BEST ANSWER

Capture the match using parenthesis, and assign it to the $year all in one step:

use strict;
use warnings;

my $whole = "The year is 2020 for now!";
my ( $year ) =  $whole =~ /(\d{4})/;
print "The year is $year for now!\n";
# Prints:
# The year is 2020 for now!

Note that I added this to your code, to enable catching errors, typos, unsafe constructs, etc, which prevent the code you showed from running:

use strict;
use warnings;
1
vkk05 On

Here is another way to capture it. Which is somewhat similar to @PYPL's solution.

use strict;
use warnings;

my $whole = "The year is 2020 for now!";

my $year;
($year = $1) if($whole =~ /(\d{4})/);

print $year."\n";
print "The year is $year for now!";

Output:

2020
The year is 2020 for now!
1
PYPL On

you have to capture it into a group

$whole="The year is 2020 for now!";
$whole =~ m/(\d{4})/;
$year =  $1;
print ("The year is $year for now!");