Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing regex result in a new variable

Tags:

regex

perl

The below program is to rearrange a string. For line 8, I am trying to store the results of a regex into a new variable $newdate, but when $newdate is printed in line 9, it only displays a 1. How can I change my code so that $newdate will store the $date value from the regex operation?

1 #!/usr/bin/perl
2 
3 # This program changes the date format from mm/dd/yyyy to yyyy,mm,dd
4 
5 $date = '21/11/2011';
6 print "Current: $date\n";
7
8 $newdate = $date =~ s/(..)\/(..)\/(....)/$3,$2,$1/;
9 print "New: $newdate\n";
like image 304
kurotsuki Avatar asked Nov 21 '11 00:11

kurotsuki


2 Answers

You could also do it like this :

my $date = '21/11/2011';
print "Current: $date\n";
my $newdate;
($newdate = $date) =~ s/(..)\/(..)\/(....)/$3,$2,$1/;
print $newdate;
like image 105
FailedDev Avatar answered Oct 06 '22 08:10

FailedDev


Since Perl 5.13.2, non-destructive substitution can be specified through the s///r modifier so a copy of the post-substitution string is assigned instead of the number of matches. It also prevents the original string from being modified, which means the two assignments have the same behavior:

( my $new_date = $date ) =~ s<(..)/(..)/(....)><$3,$2,$1>; # Pre-5.13.2

  my $new_date = $date =~ s<(..)/(..)/(....)><$3,$2,$1>r;  # Post-5.13.2

From perldoc perl5132delta:

Non-destructive substitution

The substitution operator now supports a /r option that copies the input variable, carries out the substitution on the copy and returns the result. The original remains unmodified.

my $old = 'cat';
my $new = $old =~ s/cat/dog/r;
# $old is 'cat' and $new is 'dog'
like image 22
Zaid Avatar answered Oct 06 '22 10:10

Zaid