c84032002 has asked for the wisdom of the Perl Monks concerning the following question:

Patient Monks, I thought my creation of "my $sftp..." was OK,but the later use of it in "$sftp->ls..." engendered the Global symbol error listed at the end (below). Maybe I don't really understand the ideas relating to local/global. Any help would be appreciated.
#!/usr/bin/perl use strict; use Net::SFTP; my $host = 'sftp.section111.cms.hhs.gov'; my $user = 'myUser'; my $pass = 'myPass'; #open connection eval { #timeout if no response within 120 seconds $SIG{ALRM} = sub {die "Net::SFTP timed out\n"}; alarm(120); my $sftp = Net::SFTP->new($host,user =>$user,password=>$pass, ssh_args=>[port=>10022],debug =>0) || die "Can't connect $ [at] \n" +; alarm(0); }; if ($@) { alarm(0); chomp( $@ ); die("Error: $@ trying to connect to CMS \n"); } else { $sftp->ls("/000014928/response/prod/query-only" , sub { print $_[0] +->{longname}, "\n" }); die("Success: $@ has connected to CMS \n"); } /csapps055/gentran/test/script $ demo5.pl Global symbol "$sftp" requires explicit package name at demo5.pl line +25. Execution of demo5.pl aborted due to compilation errors.
  • Comment on local creation still triggers "requires explicit package name" error
  • Download Code

Replies are listed 'Best First'.
Re: local creation still triggers "requires explicit package name" error
by choroba (Cardinal) on May 28, 2010 at 15:46 UTC
    The creation is OK, but it happens inside the eval block (it is lexically local). Therefore, $sftp is not accessible from outside the block.
      I figured that was it. But I used the Eval approach to allow me some measure of monitoring and control. The script will be in production and automated though our Scheduling system. Is there a way to create a dummy or placeholder version of $sftp at the very beginning and then replace it by the actions in the Eval block?
        Just declare it (with my $sftp;) before your eval and remove the my from inside the eval.
Re: local creation still triggers "requires explicit package name" error
by Khen1950fx (Canon) on May 29, 2010 at 06:13 UTC
    This worked for me. I tried to condense it a little; also, I turned debugging on:
    #!/usr/bin/perl use strict; use warnings; use Net::SFTP; use YAML; use YAML::Dumper; my $host = 'localhost'; my $user = 'user'; my $pass = 'password'; eval { $SIG{ALRM} = sub { die "Net::SFTP timed out\n" }; alarm 2; my $sftp = Net::SFTP->new( $host, user => $user, password => $pass, debug => 1, ); my $dumper = YAML::Dumper->new; $dumper->indent_width(4); print $dumper->dump( $sftp->ls('/usr/lib/perl5') ); }; if ($@) { chomp $@; die "Error: $@ trying to connect to CMS\n"; } else { print "All done!\n"; }