in reply to What's so wrong with this (dereferencing)code?

You are trying to use symbolic references which are forbidden under strict refs

In most cases it's better to just use hash values.

hash slices make this easy:

my %time; @time{ qw(sec min hour ...) } = localtime(time);

Edit

or

my %time; my @pad = qw (sec min hour day month); @time{ @pad } = localtime(time);

Please note how this is more DRY than your redundant code.

The reason why symbolic references are deactivated by default "strictness" is that they result in very hard to spot errors.°

If you really need this kind of meta programming, you can still reactivate it with no strict 'refs' within the local scope.¹

Update

And to why it doesn't work with private lexicals, I suppose it has to do with the history of Perl 4 to 5, the former didn't have strict or lexical vars.

Cheers Rolf
(addicted to the Perl Programming Language :)
see Wikisyntax for the Monastery

°) Especially people inexperienced to hashes are prone to this.

FWIW: I've seen languages where this was the only way to emulate hashes, but Perl is not one of them.

¹) though you can already do all of this with %package:: stash or PadWalker or eval constructs

Replies are listed 'Best First'.
Re^2: What's so wrong with this (dereferencing)code? (Symbolic Refs)
by Maelstrom (Beadle) on Jun 26, 2024 at 12:34 UTC
    I'm not 100% sure what you mean by DRY here, but I'll concede my code is only elegant from the perspective of the programmer not wanting to rewrite already written code rather than future readers. Now $_ = zeropad($_) for $sec, $min, $hour, $day, $month; OTOH? That's what I'm talking about! One added line, understandable at first glance and I've learnt a new construct. I'm also pleased to have learnt about hash slices of course but kind of overkill for solving this specific problem.
      DRY = Don't repeat yourself

      Symbolic references are just implicit hash lookups, doing them explicitly is better in the vast majority of cases.

      The for-solution you showed is aliasing which has similarities to referencing, but should not be confused.

      Update

      > Now $_ = zeropad($_) for $sec, $min, $hour, $day, $month;

      > OTOH? That's what I'm talking about!

      No you weren't.

      But FWIW, aliasing it's also feasible with hash values.

      Consider

      $_ = zeropad($_) for values %time

      and revaluate the clarity of concise code.

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      see Wikisyntax for the Monastery

        > Now $_ = zeropad($_) for $sec, $min, $hour, $day, $month;
        > OTOH? That's what I'm talking about!

        No you weren't.

        "That's what I'm talking about!" is an American idiom that expresses delight or approval. He wasn't saying it was the topic of previous remarks.