W
wana
I am packaging a set of commonly used functions to make my code a
little more easy to read. I called a package function with another
package function and the arguments I passed to it were not in @_ as
expected. I imagine if I passed by reference it might work or maybe I
need to use an array global to the package instead of @_, but those
solutions will take away from the simplicity I was hoping for. My
background is in C++ where this would be a normal way of doing things.
I found the chapter on symbol tables and packages in Programming Perl
to be a little confusing, but I thought that's where the answer would
be.
Here's the package (with irrelevant code removed). The problem comes
up when ReplaceInFile('one','two','file1','file2') calls LoadFromFile.
LoadFromFile does not receive any of the passed arguments.
package myfunctions
..
..
..
sub LoadFromFile
#takes array reference and file name as argument
#and clears array and fills array with file contents
{
my ($array, $filename) = @_;
open my $file, '<', $filename or die "Couldn't open $filename:
$!";
@{$array} = <$file>;
close $file or die "Error closing $filename: $!";
}
..
..
..
sub ReplaceInFile
{
#parameters
my $target = shift; #string to search for to replace
my $source = shift; #string to replace with
my $infile = shift;
my $outfile = shift;
#private variables
my @workspace;
LoadFromFile(@workspace,$infile);
foreach(@workspace) {s/$target/$source/g;}
SaveToFile(@workspace,$outfile);
}
1;
Thanks!
wana
little more easy to read. I called a package function with another
package function and the arguments I passed to it were not in @_ as
expected. I imagine if I passed by reference it might work or maybe I
need to use an array global to the package instead of @_, but those
solutions will take away from the simplicity I was hoping for. My
background is in C++ where this would be a normal way of doing things.
I found the chapter on symbol tables and packages in Programming Perl
to be a little confusing, but I thought that's where the answer would
be.
Here's the package (with irrelevant code removed). The problem comes
up when ReplaceInFile('one','two','file1','file2') calls LoadFromFile.
LoadFromFile does not receive any of the passed arguments.
package myfunctions
..
..
..
sub LoadFromFile
#takes array reference and file name as argument
#and clears array and fills array with file contents
{
my ($array, $filename) = @_;
open my $file, '<', $filename or die "Couldn't open $filename:
$!";
@{$array} = <$file>;
close $file or die "Error closing $filename: $!";
}
..
..
..
sub ReplaceInFile
{
#parameters
my $target = shift; #string to search for to replace
my $source = shift; #string to replace with
my $infile = shift;
my $outfile = shift;
#private variables
my @workspace;
LoadFromFile(@workspace,$infile);
foreach(@workspace) {s/$target/$source/g;}
SaveToFile(@workspace,$outfile);
}
1;
Thanks!
wana