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

the following line of code generates a syntax error, any way to fix it without declaring another scalar as the junk key only exists for me to toss random values in as needed and i know that the library is importing the hash correctly.
foreach $common::loaded{junk} (@modules)

Replies are listed 'Best First'.
Re: syntax error on foreach
by Roy Johnson (Monsignor) on Mar 29, 2004 at 17:55 UTC
    You can only use a simple scalar variable as a foreach index. You could rewrite it to use the implicit index variable $_, but you could also just inline-declare a lexical variable which would exist only in the loop:
    foreach my $m (@modules) { ... }
    Why the phobia about declaring a new variable?

    The PerlMonk tr/// Advocate
      You can only use a simple scalar variable as a foreach index.

      However, there are ways to "subvert" this, if you're determined. Here are two possible scenarios (by no means they are perfect - there can be issues with dynamic scoping (local)).

      If you don't need aliasing:

      { local $common::loaded{junk}; for (@modules) { $common::loaded{junk} = $_; # ... } }

      If you need aliasing (requires Array::RefElem):

      use Array::RefElem 'hv_store'; { local $common::loaded{junk}; for (@modules) { hv_store %common::loaded, 'junk', $_; # ... } }

      Anyway, this is bad advice ;)