http://www.perlmonks.org?node_id=152067


in reply to Whether to use local()

My question is whether you should be concerned with scope if $new_mail needs to be shared between sub update_mail_list and sub read_mail_list etc.
One trick I sometimes use to share a variable among multiple subroutines, without making it a package variable is to enclose all of them in a block.
{ my $new_mail; sub update_mail_list { # uses $new_mail } sub read_mail_list { # uses $new_mail } }
What do monks think about this style?

Thanks,
/prakash

Replies are listed 'Best First'.
Re:x2 Whether to use local()
by grinder (Bishop) on Mar 15, 2002 at 20:05 UTC
    I was wondering if someone was going to bring this up. To me, this is the best way to share a variable between two (or more) subroutines.

    Just bear in mind, though, that you may receive puzzling errors regarding $new_mail being undefined, depending on where this code appears in the file, and how and when control gets passed to update_mail_list() or read_mail_list().

    Best practices would suggest that rathing than enclosing the variable and the referring subs in bare { } braces, you should use a BEGIN { } block. This will ensure that $new_mail gets set up on the lexical pad before you get around to using it.


    print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u'
Re (tilly) 2: Whether to use local()
by tilly (Archbishop) on Mar 16, 2002 at 14:31 UTC
    I use this as well.

    But don't if you are going anywhere near mod_perl. Else much grief awaits you...

      That should only be a problem if you do that in an Apache::Registry script (and any similar beasts, if they exist). If its in a module use'd by an A::R script (and maybe even in a non A::R handler?), it should be ok (if I'm not mistaken, and if you're careful).