Eliana Lopez
Eliana Lopez

Reputation: 171

Perl Regex Variable Replacement printing 1 instead of desired extraction

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?

Upvotes: 4

Views: 100

Answers (3)

vkk05
vkk05

Reputation: 3222

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!

Upvotes: 0

Timur Shtatland
Timur Shtatland

Reputation: 12465

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;

Upvotes: 2

PYPL
PYPL

Reputation: 1859

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!");

Upvotes: 0

Related Questions