I want my code to escape from a recursive subroutine after a specific iterations
This is my my test code:
#!/usr/bin/perl
use strict;
&sub();
my $count = 0;
sub sub
{
if ( $count lt 1 )
{
print "This statment is visible \n";
$count++;
&sub();
}
else
{
return;
}
}
THis gives below output and I am happy with that:
This statment is visible
But If I use the #!/usr/bin/perl -w, then it gives me hte output but also gives me a warning:
Use of uninitialized value $count in string lt at sub.pl line 9.
This statment is visible
Quistion 1: How to get rid of above warning.
Now, Above code was my test code and I want to apply the same logic to my actual code below:
In short, I want to resolve a hostname to its IP address. If it doesn’t work, then i want to append the domain name (.my.company.net) to the hostname and then try the name resoltuion.
However, my above code (in some cases, don’t know why) goes into infinite deep recursion and eats up the whole memory. My VM becomes unresponsive and I have to reboot it to get it back working.
Hence, I want to break free from the recursive sub after one iteration rather than doing infinite recursion.
Here is the code:
#!/usr/bin/perl -w
use strict;
my $IP = to_ip("abcdefgh");
print $IP."\n";
my $count = 0;
sub to_ip
{
if ( $count lt 1 )
{
use Socket;
my $hostname = shift;
my $packed_ip = gethostbyname($hostname);
if ( defined $packed_ip )
{
sprintf inet_ntoa($packed_ip);
}
else
{
$hostname .= ".my.company.net";
to_ip($hostname);
}
$count++;
}
else
{
return;
}
}
Aobve code gives me below warning and then again get stuck. I have to reboot hte VM to get it back on.
Useless use of sprintf in void context at get_deleted_list.pl line 98.
please ignore the line number in above warning. it is referring to the sprintf in my sub
Question 2: How to break free from my sub after one iteration. I dont care whether I get the result from the sub but I want to come out of it after one iteration.
Thanks.
I think a simple loop-based solution would be more straightforward:
This simply tries all the alternatives in order until one succeeds, at which point it returns the desired string. (BTW, is
sprintfreally necessary here?). If you fall out of the loop without a successful call togethostbyname, you return undef implicitly.