To answer your question more directly, in the first case, Perl runs the subroutine once, when the line of code you showed is run, then prepends
'value 1' to the result and stores that in the hash. You can easily prove this thusly:
#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;
my $hash = { key => ' value1 '.get_value2()};
say $hash->{key};
say $hash->{key};
say $hash->{key};
$hash = { key => ' value2 '.get_value2()};
say $hash->{key};
say $hash->{key};
say $hash->{key};
sub get_value2 {
return rand();
}
Output:
value1 0.557144237523065
value1 0.557144237523065
value1 0.557144237523065
value2 0.0543176085661514
value2 0.0543176085661514
value2 0.0543176085661514
Every time my
get_value2 is called, it will return a different random number, but you can see in the output that the value printed changed only when I re-set the hash, not each time the hash was accessed.
But I agree that this smells like an XY Problem. What are you actually trying to accomplish (or what bug are you actually attempting to identify) here?
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.