http://www.perlmonks.org?node_id=11104683


in reply to The error says the value is uninitialized, but it works anyway

The homework question just defines @colors and @drop and says to remove the things in drop from colors, that's it.

If perl was math we could say:


@colors - @drop = @colors

But perl is perl so we have to say:

@colors = -@drop + @colors

Perl can do that, like this:

@colors = (miniature @drop program here) @colors

The flow of information goes:
      __<________________________<__
   #4/                              \#3
@colors = (miniature > program > here) @colors
         #2\__<___________________<___/#1

The mini program goes inside map {} like:

@colors = map { my $x = join '|', @drop; /$x/ ? () : $_ } @colors;

Unrolled:

@colors =
  map {
    my $x = join '|', @drop; # make a regex
    /$x/ ? () : $_           # simpler than it looks
  }
@colors;

  • Comment on Re: The error says the value is uninitialized, but it works anyway

Replies are listed 'Best First'.
Re^2: The error says the value is uninitialized, but it works anyway
by haukex (Chancellor) on Aug 19, 2019 at 11:33 UTC
    my $x = join '|', @drop; /$x/ ? () : $_

    While this may work for the example in the root node, it's of course pretty inefficient to build the regex on every iteration of the loop. And, the regex will match more than fixed strings, because it doesn't escape metacharacters and isn't anchored - see Building Regex Alternations Dynamically (as has been mentioned several times already). Plus, map { ... ? () : $_ } is perhaps better written as grep { not ... }.

Re^2: The error says the value is uninitialized, but it works anyway
by AnomalousMonk (Bishop) on Aug 19, 2019 at 15:15 UTC
    Unrolled: ...

    <quibble>
    Use of this word suggests "loop unrolling", but there's none of that going on. Instead, the source is being re-formatted and spiced up with some comments.
    </quibble>


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