Well, depends on what you want to do.
I quote, perldoc -f my:

A "my" declares the listed variables to be local (lexically) to the enclosing block, file, or "eval".

Let the code speak:
Run this code, study this code... :)

#!/usr/bin/perl #Is you is, or is you ain't, my foobar? #The dope on scope. baz(); #call baz. sub baz { my $foobar="I feel Baz!\n"; print $foobar; #$foobar is now lexically scoped for #the whole subroutine block. if (1) { #This is another block, it belongs to if. my $foobar="I am the FooMan!\n"; print $foobar; #$foobar is now lexically scoped #for this if block; } print $foobar; if ("I own several pairs of pants") { #That ^^^^ is another if, and this is its block my $foobar="I am the BarMan!\n"; print $foobar; #$foobar is now lexically scoped for this if block; } print $foobar; }

Now, what I would do for your little file opener is

sub openFile { my @entries; #is now lexically scoped for the entire subroutine; if ($file1) { open FH, "$file1" or die $!; @entries = <FH>; close FH; } if ($file2) { open FH, "$file2" or die $!; @entries = <FH>; #Replace all the entries? what? close FH; } }

Get it? Also, there are many flaws with the openFile code, but I digress
Have fun!


In reply to Re: where to declare a variable... by Dylan
in thread where to declare a variable... by kiat

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.