in reply to Another scoping issue: How do I send 2 variables to my sub and use both.

As detailed in DESCRIPTION in perlsub, variables passed into a subroutine are stored in the special @_ array. The shift at the start of your subroutine implicitly accesses this array. Since $nic is presumably a hash reference and thus a scalar, you could access it with:

sub getPlatformFiles { my $plat_in = shift; my $nic = shift; my @list;

A style I prefer when not using OO-style programming is to use an list assignment rather than a shift, but this is wholly subjective:

sub getPlatformFiles { my ($plat_in, $nic) = @_; my @list;

There are some potential complexities involved in scoping here, which may bite you if you are incautious and use the same variable names in a script and a subroutine. Note the following is for demonstration purposes and using this approach without good reason can result in some painful bug hunting. If you declare a variable with my in scoping using that contains a subroutine, that subroutine can see all variables in that scope, and hence the following works:

#!/usr/bin/perl use strict; use warnings; my $variable = "Hello\n"; outputter(); sub outputter { print $variable; }

This is because the scope of $variable is at the script level and contains the subroutine definition. On the other hand, the following will output an error message:

#!/usr/bin/perl use strict; use warnings; sub outputter { print $variable; } my $variable = "Hello\n"; outputter();
because the variable is not declared prior to its use in the subroutine. These behaviors allow for some very powerful structures called closures.

Replies are listed 'Best First'.
Re^2: Another scoping issue: How do I send 2 variables to my sub and use both.
by MikeDexter (Sexton) on Feb 05, 2010 at 17:40 UTC

    I have tried it both ways and I am getting a message about "use of uninitialized value in concat......"

    sub getPlatformFiles { # my ($plat_in, $nic_in) = @_; my $plat_in = shift; my $nic_in = shift; my @list; print "<$plat_in>\n"; #debugging print "<$nic_in>\n"; #debugging if ($plat_in =~ /RedHat/) { @list = ("/etc-test/resolv.conf", "/etc-test/sysconfig/network-scripts/ifcfg-$nic->{de +vice}"); } return @list; }

    The first debugging has the correct value but the second is blank empty. It prints <>

      "/etc-test/sysconfig/network-scripts/ifcfg-$nic->{device}");

      should read

      "/etc-test/sysconfig/network-scripts/ifcfg-$nic_in->{device}");

      - you missed a search and replace. If you are using strict and it did not get caught, that would be for the reason I detailed before.

      If print "<$nic_in>\n"; is not outputting something that looks like <HASH(0x236e88)>, then you are passing it an undefined value. Are you calling the subroutine with something that looks like getPlatformFiles($platform,$nic);? Are you sure $nic is defined?