Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 985
Eliana Lopez Avatar asked Oct 19 '25 08:10

Eliana Lopez


1 Answers

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;
like image 122
Timur Shtatland Avatar answered Oct 21 '25 23:10

Timur Shtatland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!