Hi Monks,

During development, I noticed a behavior of eval that I had not expected

use strict; use warnings; my %h = (a => 1, b => 2, c => 3); sub clone_h { print "cloning \%a\n"; return +{%h}; } while (my ($key, $val) = each(%{clone_h()})) { print("$key => $val\n"); }
This results in an infinite loop, printing
cloning %a b => 2 cloning %a c => 3 cloning %a a => 1 cloning %a c => 3 cloning %a a => 1 cloning %a a => 1 cloning %a b => 2 cloning %a c => 3 ...

Obviously, clone_h() is called again and again. Of course, I can work around this by first saving the result of clone_h() in a temp variable and then put the variable into the each(). But why does each() not just evaluate its argument and then work on the result?

I tried this with perl 5.10, 5.14 and 5.38.

But: The corresponding code using an array and foreach() works as expected:

use strict; use warnings; my @a = qw(a b c); sub clone_a { print "cloning \@a\n"; return [@a]; } foreach my $entry (@{clone_a()}) { print "$entry\n"; }

Why does each (but not foreach) it work like that? Why is a temporary variable forced (which seems redundant to me)?

2023-12-06 Retitled by Discipulus, as per Monastery guidelines
Original title: 'Why does eval() always re-evaluate its argument?'


In reply to Why does each() always re-evaluate its argument? by Darkwing

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.