Wednesday, 15 September 2010

perl - Escape from a recursive subroutine -



perl - Escape from a recursive subroutine -

i want code escape recursive subroutine after specific iterations

this my test code:

#!/usr/bin/perl utilize strict; &sub(); $count = 0; sub sub { if ( $count lt 1 ) { print "this statment visible \n"; $count++; &sub(); } else { return; } }

this gives below output , happy that:

this statment visible

but if utilize #!/usr/bin/perl -w, gives me hte output gives me warning:

use of uninitialized value $count in string lt @ sub.pl line 9. statment visible

quistion 1: how rid of above warning.

now, above code test code , want apply same logic actual code below:

in short, want resolve hostname ip address. if doesn't work, want append domain name (.my.company.net) hostname , seek name resoltuion.

however, above code (in cases, don't know why) goes infinite deep recursion , eats whole memory. vm becomes unresponsive , have reboot working.

hence, want break free recursive sub after 1 iteration rather doing infinite recursion.

here code:

#!/usr/bin/perl -w utilize strict; $ip = to_ip("abcdefgh"); print $ip."\n"; $count = 0; sub to_ip { if ( $count lt 1 ) { utilize socket; $hostname = shift; $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 , 1 time again stuck. have reboot hte vm on.

useless utilize of sprintf in void context @ get_deleted_list.pl line 98.

please ignore line number in above warning. referring sprintf in sub

question 2: how break free sub after 1 iteration. dont care whether result sub want come out of after 1 iteration.

thanks.

i think simple loop-based solution more straightforward:

sub to_ip { utilize socket; $hostname = shift; $suffix ("", ".my.company.net") { $packed_ip = gethostbyname("$hostname$suffix"); next unless defined $packed_ip; homecoming sprintf inet_ntoa($packed_ip); } }

this tries alternatives in order until 1 succeeds, @ point returns desired string. (btw, sprintf necessary here?). if fall out of loop without successful phone call gethostbyname, homecoming undef implicitly.

perl

No comments:

Post a Comment