Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Comment on

( #3333=superdoc: print w/ replies, xml ) Need Help??
If you are using multiple files in your script and you assume that "use strict" from the main script will automatically affect all the other scripts, you will run afoul of this scoping issue. The scripts below will exhibit different behavior with respect to globals when strict and my are used than when strict and my are not used. If we really want to use $z in our main scope as a global, we should either pass a reference to it in our sub call (and modify it in place), or set its value based on the return value of our sub call. Or we could not use strict, but we should use strict and figure out a better way to handle our data than indiscriminate use of globals.
#!/usr/bin/perl -w #this is scope1.pl use strict; #comment out require 'scope2.pl'; my $z = 0; #comment out, we could also leave this # undef, but that generates a bunch of warnings for my $x (1..5) { my $y = multiply( $x ); print "$x * 3 : $y : $z\n"; } _______________________________________ #this is scope2.pl sub multiply { $this = shift; $z = $this * 3; } 1;

In reply to (ichimunki) Re: Need some help with a dodgy variable by ichimunki
in thread Variable Scope by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others romping around the Monastery: (7)
    As of 2014-09-21 08:33 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      How do you remember the number of days in each month?











      Results (167 votes), past polls