4

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?

Eliana Lopez
  • 161
  • 1
  • 1
  • 8

3 Answers3

2

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;
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
0

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!");
PYPL
  • 1,819
  • 1
  • 22
  • 45
  • Ideally, you don't want to use `$1` without confirming that a match has occurred (since it can lead to weird, hard to debug results), especially since it's so easy to do (as seen in Timur's answer). – ikegami Sep 22 '20 at 12:42
0

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!
vkk05
  • 3,137
  • 11
  • 25
  • This is better than PYPL's answer because it doesn't use `$1` without confirming that a match has occurred, but see Timur's answer for a much cleaner way of doing the same thing. – ikegami Sep 22 '20 at 12:43