in reply to Re^2: Why is "any" slow in this case?
in thread Why is "any" slow in this case?

That's how magic variables works. Every time you can read a variable with get magic, a getter function is called to populate it first. Every time you write to a variable with set magic, a setter function is called to process the new value afterwards.

use v5.40; use Variable::Magic qw( cast wizard ); my $wiz = wizard( get => sub { say sprintf 'getter called for %X', refaddr( $_[0] ); ${ $_[0] } = int( rand( 100 ) ); }, ); my $var; say sprintf '`$var` is %X', refaddr( \$var ); cast $var, $wiz; for ( 1 .. 4 ) { say "Loop: $_"; say "`\$var` has value $var"; }
`$var` is 5F5668128E20 Loop: 1 getter called for 5F5668128E20 `$var` has value 22 Loop: 2 getter called for 5F5668128E20 `$var` has value 62 Loop: 3 getter called for 5F5668128E20 `$var` has value 44 Loop: 4 getter called for 5F5668128E20 `$var` has value 70

The alternative to magic would be to preemptively copy substrings of the matched string into $`, $&, $' and $n, $+{name} and $-{name}.

Replies are listed 'Best First'.
Re^4: Why is "any" slow in this case?
by LanX (Saint) on Jul 28, 2025 at 16:54 UTC
    Well the question could be rephrased into

    Why do we need $1 to be magic, when it's read-only?

    Threading?

    > would be to preemptively copy substrings of the matched string into

    if this is about avoiding overhead for optional variables, retrieving it just once on demand would be sufficient.

    The OP is accessing the same $1 4 times in a row.

    Update

    the code examples were updated in the parent post while I was replying.

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

      Why do we need $1 to be magic, when it's read-only?

      We don't need it to be. As I mentioned, the alternative would be to make make a copy of the matched text on match. The down side is that this would happen even if $1 isn't used. Same goes for all the other vars I mentioned.

      if this is about avoiding overhead for optional variables, retrieving it just once on demand would be sufficient.

      That's not how magic works. Get magic changes a variable from something that stores a value, to a function that produces the value on demand. You can either store the value in the var, or generate it each time the var is accessed.

        OK I always took the word "magic" as term for various "implementation quirks" in Perl and not as a well defined mechanism.

        Variable::Magic suggests otherwise ...

        ... learning every day something new. :)

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