Search code examples
regexperlvariablesperl5.8

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?


Solution

  • 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;