This article is in response to the following question posted in the Perl community group on LinkedIn:
Iβm new to PERL and trying to understand recursive subroutines. Can someone please explain with an example (other than the factorial π ) step by step, how it works? Thanks in Advance.
Below, are some very simplified code examples in Perl, Ruby, and Bash.
A listing of the files used in these examples:
blopez@blopez-K56CM ~/hello_scripts
$ tree .
βββ hello.pl
βββ hello.rb
βββ hello.sh
0 directories, 3 files
blopez@blopez-K56CM ~/hello_scripts $
Recursion example using Perl:
β How the Perl script is executed, and itβs output:
blopez@blopez-K56CM ~/hello_scripts $ perl hello.pl "How's it going!"
How's it going!
How's it going!
How's it going!
^C
blopez@blopez-K56CM ~/hello_scripts $
β The Perl recursion code:
#!/usr/bin/env perl
use Modern::Perl;
my $status_update = $ARGV[0]; # get script argument
sub hello_world
{
my $status_update = shift; # get function argument
say "$status_update";
sleep 1; # sleep, or eventually crash your system
&hello_world( $status_update ); # execute myself with argument
}
&hello_world( $status_update ); # execute function with argument
Recursion example using Ruby:
β How the Ruby script is executed:
blopez@blopez-K56CM ~/hello_scripts
$ ruby hello.rb "Doing great!"
Doing great!
Doing great!
Doing great!
^Chello.rb:7:in `sleep': Interrupt
from hello.rb:7:in `hello_world'
from hello.rb:8:in `hello_world'
from hello.rb:8:in `hello_world'
from hello.rb:11:in `'
blopez@blopez-K56CM ~/hello_scripts $
Note: In Rubyβs case, stopping the script with CTRL-C returns a bit more debugging information.
β The Ruby recursion code:
#!/usr/bin/env ruby
status = ARGV[0] # get script argument
def hello_world( status ) # define function, and get script argument
puts status
sleep 1 # sleep, or potentially crash your system
return hello_world status # execute myself with argument
end
hello_world status # execute function with argument
Recursion example using Bash:
β How the Bash script is executed:
blopez@blopez-K56CM ~/hello_scripts $ bash hello.sh "..nice talking to you."
..nice talking to you.
..nice talking to you.
..nice talking to you.
^C
blopez@blopez-K56CM ~/hello_scripts $
β The Bash recursion code:
#!/usr/bin/env bash
mystatus=$1 # get script argument
hello_world() {
mystatus=$1 # get function argument
echo "${mystatus}"
sleep 1 # breath between executions, or crash your system
hello_world "${mystatus}" # execute myself with argument
}
hello_world "${mystatus}" # execute function with argument


Leave a comment