A simple perl recursion example

Have a test about what will happen if a script is calling to run it self when it is running:

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

print "******\n";
perl $0;

The result will be kind of infinite recursion, keep printing out the * .

3 Comments

Very cool. But what if your perl is in a different path? :-o


print "lel.\n";
system $^X . " $0";

Should take care of it for you.

So, you solution would eventually run out of memory; or would hit the limit of number of processes your os will allow. If you really want it to be infinite; you should use exec; which would basically be doing a tail call optimization. (Since nothing after the exec will get called; and the process memory space is reused.)

#!/usr/bin/perl 

use v5.12.0;
use warnings;

say  'foo:'.($ARGV[0] // 'none');
exec join(' ' ,$^X, $0 , $ARGV[0]+1) ;

Leave a comment

About flymike

user-pic Keep it simple, stupid.