in reply to Re^3: "my" declaration problem
in thread "my" declaration problem

The following code might have been autogenerated. It's not even really confusing and it works exactly as advertised:

use Guard; use File::Temp 'tempfile'; sub frobnicate { my ($fh,$name) = tempfile(); print {$fh} "Hello"; close $fh; my $atexit = guard { print "Removing '$name'"; unlink $name; }; my ($fh,$name) = tempfile(); print {$fh} "World"; close $fh; my $atexit = guard { print "Removing '$name'"; unlink $name; }; } print "Frobnicating"; frobnicate(); print "Frobnicating done, and cleaned up"; __END__ Frobnicating Removing 'C:\Users\Corion\AppData\Local\Temp\JPUN_wEVOo' Removing 'C:\Users\Corion\AppData\Local\Temp\eUuaGV_5sj' Frobnicating done, and cleaned up

Of course, there is no way to get at the first instances of $fh, $name and $atexit.

And if I were autogenerating that code, why would I bother with naming the variables $name1, $name2 etc. when they are just for later customization anyway?

Replies are listed 'Best First'.
Re^5: "my" declaration problem
by LanX (Saint) on Apr 25, 2017 at 20:38 UTC
    > if I were autogenerating that code ...

    Or not using my at all or even better putting each snippet into a block.

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Je suis Charlie!

      Not really.

      Not using my would make the first $atexit trigger immediately instead of when leaving the sub frobnicate.

      Putting things in their own blocks would make it impossible to use $name or whatever other effect of creating the file, and also would trigger the $atexit block when leaving that block instead of when leaving that function.

        I didn't know or used Guard.pm and have my doubts ...

        Cheers Rolf
        (addicted to the Perl Programming Language and ☆☆☆☆ :)
        Je suis Charlie!