in reply to Matching specific strings (are subs a good idea?)
Hello zarath,
In Perl, a variable declared with my has lexical scope, meaning it is not visible outside the scope in which it is declared. So when you declare my $firstname inside the main for loop, that variable goes out of scope (i.e., cannot be seen) when the loop block ends. As the subroutines are outside of this scope, they can’t “see” $firstname. Actually, this is a GOOD THING, as it makes it less likely that $firstname will be accidentally overwritten in some unrelated part of the code.
When using subroutines, it is standard practice to pass variables in like this:
... my $bdate = fetchBD($firstname, $lastname, $email); ... sub fetchBD { my ($firstname, $lastname, $email) = @_; while (my $line = <QR>){ ...
This technique creates local copies of the 3 variables passed in. See perlintro#Writing-subroutines.
But the main problem with the code shown is with the logic of the subroutines. When the while loop within the main for loop processes a line of input, it calls subroutines to extract the desired information. But within each of those subroutines, reading of that same file continues, line-by-line, in a another while loop, until the input is exhausted! In fact, the while loops in the subroutines are not needed. You should rather just pass in the input line along with the other data:
... my $bdate = fetchBD($line, $firstname, $lastname, $email); ... sub fetchBD { my ($line, $firstname, $lastname, $email) = @_; my $fns = index($line,'FirstName'); ...
It will actually be a lot easier to extract the data using regular expressions than using index and substr. It will help if you give some sample data from one of the xml files and from the text file. (Also note that, as a general rule, it’s better to extract xml data using a dedicated module such as XML::LibXML.)
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|