Variable in a Perl function has an unexpected value outside the function

dbi, perl, recursion

Solution

`use strict`, avoid global variables. In other words: you are reusing the global `$result`, resetting its value in each call to the subroutine.

Problem

So, I'm new to Perl. I'm attempting to create a recursive subroutine. The logic seems simple: ``` sub directory_tree { my $sth = $dbh->prepare(" SELECT id, org_id, name FROM media_directories WHERE org_id = ? AND parent = ? AND bucket = ? "); $sth->bind_param(1, $_[0]); $sth->bind_param(2, $_[1]); $sth->bind_param(3, 'mfsermons.myflock2.com'); $sth->execute; $result = ''; while(my($id, $org_id, $name) = $sth->fetchrow_array()) { $result .= "<option value='$id'>$name</option>"; #377 $result .= directory_tree($org_id, $id); #378 } return $result; } $directory_tree = '<select name="folder">'; $directory_tree .= directory_tree($churchid, 0); $directory_tree .= '</select>'; ``` Why is it that when I print `$result` after line 377 that it is equal to the expected value, but when I print it on line 378, nothing appears? Shouldn't the .= operator just run the function again, and then append to the value? My best guess is that there are some scope issues in Perl I don't understand, particularly with regards to `$result`. However, for the life of me, I can't figure out what's wrong, and I have absolutely no idea where to look! When I turn on error reporting, fatals and warnings, nothing is returned. What could possibly be going wrong that I'm missing?

Original source