kathys39 has asked for the wisdom of the Perl Monks concerning the following question:

I have a perl script that is called hourly to parse some data. The code is below:
foreach $file (@filelist) { Parse::parse_file($file,$project,$date); Moving::move_file($file,$project,$date); ...

The parse_file sub is in another file. This subroutine includes the following lines:
use vars qw ($project, $date) .... return $project, $date

I want parse_file to process the data, and return the filename, the project name and a few other variables. I want these variables passed to the move_file subroutine, located in yet a third file (package). How can I get these variables (which are set in the parse_file sub) to the move_file subroutine?

Replies are listed 'Best First'.
Re: sharing variables among 2 subroutines
by locked_user sundialsvc4 (Abbot) on Nov 19, 2007 at 19:14 UTC

    The existing subroutine is returning a list of values, and the previous respondent showed you how you can capture that into another list-of my-variables.

    Another “way to do it” might be to have the parse_file subroutine return a hash that is then supplied as an input-variable to move_file. The appeal of this approach, to me, is that the order of the elements in a hash does not matter:   a hash is a collection of related values that is, by its intrinsic nature, self-describing. If you want to add another value to whatever you want to pass between the two subroutines, you can “just do it.”

    So now, your code might be something like...

    foreach $file (@filelist) { my $info = Parse::parse_file($file); Moving::move_file($info); }

    Remember that the internal comments to both modules ... which of course have been written with them and are scrupulously maintained along with the code ... must include detailed explanations of where the input- and output-hashes come from, and what they are required to contain. The subroutines should also die, and not just “behave incomprehensibly,” if their prerequisites are not met...

    Conservatum Follicum:   “The hair you save may be your own,” and you just might miss it someday...

Re: sharing variables among 2 subroutines
by dragonchild (Archbishop) on Nov 19, 2007 at 18:49 UTC
    Actually use your return variable?
    foreach my $file ( @files ) { my ($project, $date) = parse_file( $file ); move_file( $file, $project, $date ); }

    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
      I tried that. When I print out the value of project and date from the end of parse_file, they print out ok. However, if I do it after I return from parse_file (and before move_file) they are blank!