I have been pondering this for a few days now and I always seem to run into a problem when I want to use strict (which every good perl programmer should) and I have the first use of a variable inside of a loop or if statement. If I want to later print that variable or refer to it some other way I have to either declare it as a global variable or pass the results out of the specific function.

For Example:

#!/usr/bin/perl -w use strict; die "Required argument missing!\n" unless ($ARGV[0]); if ($ARGV[0] =~ /Hello/i) { my $response = "Hello to you.\n"; }else{ my $response = "Huh?\n"; } print $response;
Now if I syntax check this or run it I would get the following error.

Global symbol "$response" requires explicit package name at syn_check line 11. syn_check had compilation errors.
What is the best way to pass the variable $response out of the if statement to make it visible at another level? Remember I do not want to make the variable global either.

In reply to Best way to pass variables? by Elijah

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!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • 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, details, 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, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            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.