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.

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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.