0

my $num = 1;
cal($num);
print "$newnum\n";

sub cal{
my $num = shift;
my $newnum = $num + 1;
return $newnum;
}

is it possible to take variable $newnum and use its value outside of the sub cal. At the moment if i try and print the variable $newnum outside of the subroutine nothing is returned.

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by d5e5
0

Lexical variables declared with my are defined only within the block in which you declare them. In your script you are returning a value in a void context instead of printing it or assigning it to a variable having a scope outside the subroutine. Here is how you would assign the returned value to a variable that you can print.

#!/usr/bin/perl
use strict; 
use warnings;

my $num = 1;
my $newnum = cal($num);#Assign returned value to variable with required scope
#print "$newnum\n";#This won't work outside of cal subroutine's scope
print "New number is $newnum\n";

sub cal{
    my $num = shift;
    my $newnum = $num + 1;
    return $newnum;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.