cannot print out variable called from perl sub routine
I want to convert my foreach loop to a sub routine sub mybits
. I'm sure I am not calling this properly or for that matter setting it up as a sub.
What I want to do is return a value from the sub routine which is any one of three variables which i tested foreach part and am able to get data.
Got this mesg. I am using strict, warnings: Can't modify non-lvalue subroutine call
How do I call this sub routine to get either of my variables ($dir, $fname, $fsize)
?
Code:
my $out;
mybits (my $dir)=$out;
print mybits($dir);
print "This is mybits: $out\n";
sub mybits
{
foreach my $file( @{ $data->{file} } )
{
#my( $dir, $fname );
my( $dir, $fname, $fsize );
if( $file->{path} =~ /^(.*)\/([^\/]+)$/ )
{
$dir = $1;
$fname = $2;
$fsize = $file->{size};
}
开发者_Python百科 else
{
$dir = "";
$fname = $file->{path};
}
#print "This is the DIRECTORY: $dir\n";
#print "This is the FILE: $fname\n";
#print "This is the FILE SIZE: $fsize\n";
}
}
It is impossible to get at any of $dir
, $fname
, or $fsize
in your subroutine as written, since their scope is limited to your subroutine (specifically to the foreach
loop within your subroutine). You'll have to have your subroutine return these values. However, since these are used over and over again in a loop, you'll probably want to return all possible values. Perhaps something like:
sub mybits
{
my $return_dirs=[];
my $return_fnames=[];
my $return_fsizes=[];
foreach my $file( @{ $data->{file} } )
{
#my( $dir, $fname );
my( $dir, $fname, $fsize );
if( $file->{path} =~ /^(.*)\/([^\/]+)$/ )
{
$dir = $1;
$fname = $2;
$fsize = $file->{size};
}
else
{
$dir = "";
$fname = $file->{path};
}
#Put the relevant data into the array references that we'll return later.
push @$return_dirs,$dir;
push @$return_fnames,$fname;
push @$return_fsizes,$fsize;
}
return [$return_dirs,$return_fnames,$return_fsizes];
}
my $values=mybits();
foreach(@$values)
{
print join(",",@$_) . "\n";
}
Note: All of this assumes that the rest of the code in mybits
actually works correctly...given that the OP only provided some of the code (eg we have no idea what $data
is), I can't guarantee that this is the case.
This line:
mybits (my $dir)=$out;
tries to assign $out
to the value returned by your subroutine. This is not possible, it's not a valid lvalue hence the error. What exactly you want to do?
精彩评论