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};
}
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$fsizein your subroutine as written, since their scope is limited to your subroutine (specifically to theforeachloop 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:Note: All of this assumes that the rest of the code in
mybitsactually works correctly…given that the OP only provided some of the code (eg we have no idea what$datais), I can’t guarantee that this is the case.