http://qs1969.pair.com?node_id=11128987

thirtySeven has asked for the wisdom of the Perl Monks concerning the following question:

I have settled into using this syntax for assigning variables based on regex matches.
$foo = $1 if $foo =~ /(hello)/;
I am constantly doing this so I want to know other ways to do the same thing.
  • Comment on Looking for alternative syntax for assigning variables based on regex matches
  • Download Code

Replies are listed 'Best First'.
Re: Looking for alternative syntax for assigning variables based on regex matches
by haukex (Archbishop) on Mar 02, 2021 at 05:24 UTC
    my ($x,$y) = $foo =~ /(hello)(world)/ or die "failed to match"; if ( my ($x,$y) = $foo =~ /(hello)(world)/ ) { print $x, $y; } if ( $foo =~ /(?<x>hello)(?<y>world)/ ) { print $+{x}, $+{y}; }

    Update: The first two work like any other variable assignment, so ($foo) = $foo=~/(hello)/; works too of course. (Update 2: If assigning back to the same one variable, so does s/// and its variations.)

Re: Looking for alternative syntax for assigning variables based on regex matches
by rsFalse (Chaplain) on Mar 02, 2021 at 10:28 UTC
    With non-destructive /r modifier (and lookahead):
    perl -wle '$foo = "a hello w"; $foo = $foo =~ s/(?=.*(hello)).*/$1/sr; + print $foo'
    OUTPUT:
    hello
    And if you want only to use your capture, just:
    ...; print $foo =~ s/(?=.*(hello)).*/$1/sr;
    In the later example a value of $foo didn't change.
    *Updated

    +one more way:
    ...; $foo =~ /hello(?{ $foo = $& })/; print $foo
    Though it looks like bad practice to change a variable while it is in use.
Re: Looking for alternative syntax for assigning variables based on regex matches
by Marshall (Canon) on Mar 02, 2021 at 22:14 UTC
    An idea for you:
    use strict; use warnings; my $foo ="some hello message"; my ($hello) = $foo =~ /(hello)/; $hello //= ''; # null string if "hello" was not found __END__ $hello will be either "hello" or a null string. Better than an undef value. Amongst other things, this maintains a "printable value" for $hello. use $hello in a Boolean context. $foo is a string. Do not reuse that string variable name to mean something different. Create new Boolean variable.
Re: Looking for alternative syntax for assigning variables based on regex matches
by Anonymous Monk on Mar 02, 2021 at 13:58 UTC
    "There's More Than One Way To Do It." Tim Toady.

    However you choose to do it, make your code easy for a human reader to understand, and easy to change in one small, targeted, "git" commit. What you've written is clear enough, and I would just keep doing it.