问题
I'm trying to write in file some value taken from an array. But I'm having some error ''Can't use an undefined variables as a symbol reference at... line 81:
foreach $k (sort keys %{$value2}){
print $value4 $k." = ".%{$value2{$k}}. $value3;
sub printit{
$value1 = $_[0];#"ipadress" is a string
$value2 = $_[1];#%hash2
$value3 = $_[3];#"paquet" is a string
$value4 = $_[4];#SOURCE is the file name
foreach $k (sort keys %{$value2}){
print $value4 $k." = ".%{$value2{$k}}. $value3;
if (%{$value2{$k}} >= 2) { print $value4 "s";}
print $value4 "\n";
}
}
printit('ipadress', \%hash2, ' paquet'. SOURCE );
Could someone please indicate me what's wrong?
the things is my code is this one and it work fine. And I didn't concatanate SOURCE and it's still working fine.
print SOURCE "Ipadress #2\n\n";
foreach $k (sort keys %hash2){
print SOURCE $k." = ".$hash2{$k}." paquet";
if ($hash2{$k} >= 2) { print SOURCE "s";}
print SOURCE "\n";
}
but I'm having a lot of codes that does the same thing so I wanted to create a function to be able reduce the numbers of lines.
回答1:
Your forgot a comma or concatenation here:
print $value4 $k." = ".%{$value2{$k}}. $value3;
Perl thinks you want to use $value4 has a filehandle (symbol), and apparently $value4 is undefined. The reason it is undefined is because you assign it the value of $_[4] but you probably want $_[3] (since arrays are zero-indexed.)
It looks like you intend $value4 to be a file name for your output; if that's the case then you need to actually open that file to get a filehandle:
open my $fh, '>', $value4 or die "Could not open file $value4: $!";
...
print { $fh } $k." = ".%{$value2{$k}}. $value3;
So you have three things to fix:
Figure out why
$value4is undefined and fix that. (When you find yourself appending numbers onto the names of scalars, chances are you probably want to use an array anyway. You could use just@_directly or grab the values into an@argsarray rather than a bunch of scalars.)Figure out how you want to format your output string and use a filehandle, not a filename, for
print.Figure out how you want to serialize the hash referenced by
$value2{$k}, because printing a hash in scalar context is almost certainly not what you want to do.
(Updated suggestions after I realized you're lacking a filehandle)
来源:https://stackoverflow.com/questions/16391047/cant-use-an-undefined-value-as-a-symbol-perl