in reply to Replace a hash key if it matches a regex

foreach (keys $db_results) { my $match = $1 if $_ =~ /(BLAH\d{2}-\w)/; $db_results->{$1} = delete $db_results->{$_}; }

The  $match variable isn't used in the quoted code, so I assume this is a cut-down fragment of working code in which it is subsequently used. If so, be aware that the usage
    my $scalar = $whatever if ... ;
(conditional definition/initialization of a lexical) is a pre-state (5.10+) hack used to create a bastard state-like variable; it has all kinda weird side-effects and is officially Frowned Upon. Avoid it if you can — and you can, e.g.:
    my ($match) = $_ =~ /(whatever)/;
    do_something_with($match) if defined $match;
or (assuming you're in a loop)
    my ($match) = $_ =~ /(whatever)/;
    next unless defined $match;
    ...

Replies are listed 'Best First'.
Re^2: Replace a hash key if it matches a regex
by walkingthecow (Friar) on Sep 13, 2013 at 10:01 UTC
    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.
      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.
      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;
          ...