[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Perl realted..?



On Jan 11, 4:20 am, "s. keeling" <keel...@nucleus.com> wrote:
> ISHWAR RATTAN <rat...@cps.cmich.edu>:
>
> >  I am coming back toperlafter a long time.
>
> >  The sample code these days also uses variable attribute my as:
>
> >     my $inst = Extutils::Installed->new();
> >     my @modules = $inst->modules();
>
> >  Can any demistify 'my' for me??
>
>       -----------------------------
>            #!/usr/bin/perl
>            # this just re-implements tail -1
>            #
>            # usage:
>            #   /this/file < /some/text/file.txt
>            #
>
>            my $last;
>
>            while( <> ) {
>              $last = $_;
>            }
>
>            print $last;
>       -----------------------------
>
> Now, try with the "my $last;" *inside* the while().  That last print
> line won't have a clue what $last is.
>

That doesn't sound right to me.  Scope doesn't change in a loop.  All
of this code is in the same scope, so the print statement will work
fine.

If you move the loop to a subroutine, then the two $last variables
will be independant due to separate scopes:

my $last="foo";
$bar=scan_loop();
print $bar;
print $last;
sub scan_loop{
  my $last;
  while( <> ){
    $last=$_;
    return $last;
  }
}

This will print out the last line and then "foo" because there are two
$last values, the one in the original scope and the one in the
subroutine scope.

-pedxing


Reply to: