Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re^2: Replace a hash key if it matches a regex

by walkingthecow (Friar)
on Sep 13, 2013 at 10:01 UTC ( #1053877=note: print w/replies, xml ) Need Help??

in reply to Re: Replace a hash key if it matches a regex
in thread Replace a hash key if it matches a regex

Wait, this is new to me. Are you saying that this:
my $foo = $1 if $_ =~ /regex/;
is bad?

The only alternative to that which I know is:
if ( $_ =~ /regex/ ) { my $foo = $1; $db_results->{$foo} = delete $db_results->{$_}; }
By the way, thanks for pointing out that I was not using $match. Late night.

Replies are listed 'Best First'.
Re^3: Replace a hash key if it matches a regex
by choroba (Bishop) on Sep 13, 2013 at 10:14 UTC
    See perlsyn - Perl syntax for details:
    The behaviour of a my, state, or our modified with a statement modifier conditional or loop construct (for example, my $x if ... ) is undefined. The value of the my variable may be undef, any previously assigned value, or possibly anything else. Don't rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons.

    You can use the following:

    if (my ($match) = $_ =~ /...(...).../) { $db_results->{$match} = delete $db_results->{$_} }

    For $_, you can omit the $_ =~ part.

    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Awesome. Thanks to both of you for taking the time to correct me on this and explain it so well.
Re^3: Replace a hash key if it matches a regex
by AnomalousMonk (Chancellor) on Sep 13, 2013 at 10:15 UTC
    Are you saying ... is bad?

    Yes — or at least potentially very weird and certainly very easily avoided. I'm afraid I don't have time ATM to locate a good explanatory link. (Update: Thanks, choroba, for the link)

    The only alternative ... which I know ...

    Sorry, I added some examples of alternatives after my original reply without marking them as update material. BTW, another alternative (assuming you're in a loop):
        next unless $_ =~ /(whatever)/;
        my $foo = $1;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1053877]
[Eily]: that's one long sheband

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (7)
As of 2018-05-25 08:16 GMT
Find Nodes?
    Voting Booth?