Hello Cody Fendant,
choroba has explained what is happening, but recursion tends to be counter-intuitive and therefore hard to “grasp” or visualise. So I’ve rewritten your example code and added print statements in an attempt to make the logistics clearer:
#! perl use strict; use warnings; my %includes = ( 1 => join("\n", '<html>', '<head>', ' <include id="2">', ' <title>hello world</title>', '</head>', '<body>', '<div class="container">', ' <h1>Hello world</h1>', ' <include id="3">', '</div>', '</body>', '</html>'), 2 => '<link rel="stylesheet" href="foo.css">', 3 => '<div id="footer">copyright <include id="4"></div>', 4 => '2014', ); render(1); sub render { my $id = shift; my $html = $includes{$id}; print '-' x 10, "\nrender($id) BEFORE:\n$html\n"; $html =~ s/<include id="(\d+)">/render($1)/eg; print "render($id) AFTER:\n$html\n", '-' x 10, "\n"; return $html; }
Output:
1:27 >perl 1066_SoPW.pl ---------- render(1) BEFORE: <html> <head> <include id="2"> <title>hello world</title> </head> <body> <div class="container"> <h1>Hello world</h1> <include id="3"> </div> </body> </html> ---------- render(2) BEFORE: <link rel="stylesheet" href="foo.css"> render(2) AFTER: <link rel="stylesheet" href="foo.css"> ---------- ---------- render(3) BEFORE: <div id="footer">copyright <include id="4"></div> ---------- render(4) BEFORE: 2014 render(4) AFTER: 2014 ---------- render(3) AFTER: <div id="footer">copyright 2014</div> ---------- render(1) AFTER: <html> <head> <link rel="stylesheet" href="foo.css"> <title>hello world</title> </head> <body> <div class="container"> <h1>Hello world</h1> <div id="footer">copyright 2014</div> </div> </body> </html> ---------- 1:27 >
If you follow this through a few times, it eventually starts to make sense (no, really!). Pay particular attention to the order in which the four calls to sub render are interleaved.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
In reply to Re: Recursively executed function in regex RHS, AKA "wait, why does this work?"
by Athanasius
in thread Recursively executed function in regex RHS, AKA "wait, why does this work?"
by Cody Fendant
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |