Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re^3: Assigning a parsed date to a variable

by Laurent_R (Canon)
on Mar 30, 2017 at 21:48 UTC ( [id://1186550]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Assigning a parsed date to a variable
in thread Assigning a parsed date to a variable

The difference is context. In scalar context, a regex usually returns the number of matches or the number of substitutions, which is not what you want here. Adding parentheses creates a list context in which a regex will usually return something closer to what you want here.
  • Comment on Re^3: Assigning a parsed date to a variable

Replies are listed 'Best First'.
Re^4: Assigning a parsed date to a variable
by AnomalousMonk (Archbishop) on Mar 30, 2017 at 23:19 UTC
    Adding parentheses creates a list context ...

    This is either terminal nitpicking on my part or a confession of total ignorance, but I thought that for substitution, the
        ($x = $y) =~ s///;
    form (case B below) worked by circumventing normal operator precedence and making the value, normally a scalar, which is bound by the =~ operator into an assignment expression, which causes the substitution result to be assigned to the assignment lvalue. I.e., list context does not come into play at all. In the
        $x = $y =~ s///;
    statement (case C), the =~ operator has precedence over = and the  s/// return value, the number of substitutions in any context, is assigned. (Somewhere in my Perlish consciousness, I have the idea that substitution normally builds its result in a temporary variable, which is then copied to the bound scalar upon successful completion of the substitution. If an assignment expression is detected, the temp result is simply copied to a different destination.)

    Of course, for a  m// match operation (case A below), list context can be very important.

    c:\@Work\Perl>perl -wMstrict -le "my $y = '2017-01-29 11:30:07.370'; my $x; ;; ($x) = $y =~ m{ (\d{4}) - (\d{2} - \d{2}) \s+ (\d{2} : \d{2}) .* }xms +; print qq{A: x '$x' y '$y'}; ;; ($x = $y) =~ s{ (\d{4}) - (\d{2} - \d{2}) \s+ (\d{2} : \d{2}) .* } {$2-$1 $3}xms; print qq{B: x '$x' y '$y'}; ;; $x = $y =~ s{ (\d{4}) - (\d{2} - \d{2}) \s+ (\d{2} : \d{2}) .* } {$2-$1 $3}xms; print qq{C: x '$x' y '$y'}; " A: x '2017' y '2017-01-29 11:30:07.370' B: x '01-29-2017 11:30' y '2017-01-29 11:30:07.370' C: x '1' y '01-29-2017 11:30'


    Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1186550]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2024-04-25 12:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found