Perl::...alVars(3pm)

πŸŽ€ NAME πŸŽ€

Perl::Critic::Policy::Variables::RequireInitializationForLocalVars β€” okay bestie, this policy is here to tell you to write local $foo = $bar; instead of just local $foo;. That's the whole assignment, and she ate. πŸ’…

This page is hanging out in the User Contributed Perl Documentation section, and it's giving very "tiny policy, big saves" energy. ✨

🌸 AFFILIATION 🌸

This Policy is part of the core Perl::Critic distribution. Core. Iconic. No cap. πŸ‘‘

✨ DESCRIPTION ✨

Most people don't realize that a localized copy of a variable does not retain its original value. Literally, unless you initialize the variable when you local-ize it, it defaults to undef.

If you want the variable to retain its original value, just initialize it to itself. If you really do want the localized copy to be undef, then make it explicit. That's the vibe check, and the code says it best:

           package Foo;
           $Bar = '42';

           package Baz;

           sub frobulate {

               local $Foo::Bar;              #not ok, local $Foo::Bar is 'undef'
               local $Foo::Bar = undef;      #ok, local $Foo::Bar is obviously 'undef'
               local $Foo::Bar = $Foo::Bar;  #ok, local $Foo::Bar still equals '42'

           }

Lowkey the comments are doing the teaching here: local $Foo::Bar; is not ok because local $Foo::Bar is 'undef'; local $Foo::Bar = undef; is ok because local $Foo::Bar is obviously 'undef'; and local $Foo::Bar = $Foo::Bar; is ok because local $Foo::Bar still equals '42'. 🫢

πŸŽ›οΈ CONFIGURATION πŸŽ›οΈ

This Policy is not configurable except for the standard options. That's it. No secret knobs, no extra settings, just standard-options business. πŸ’€

πŸ‘‘ AUTHOR πŸ‘‘

Jeffrey Ryan Thalhammer <jeff@imaginative-software.com> β€” thank you for your service, king. 🫑

Copyright (c) 2005-2011 Imaginative Software Systems. All rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. The full text of this license can be found in the LICENSE file included with this module. 🌈


Okay bestie, signing off with the footer facts: this page is from perl v5.42.0, dated 2024-10-23, and its page tag is Perl::...alVars(3pm). Stay initialized, stay iconic, and make that undef explicit. mwah πŸ’‹πŸŽ€

πŸ“¦ where this page comes from