I have been playing with different styles and data structures, just trying to get a feel for perl better, and what I can do.
I have been reading Perl Objects, References and Modules by Randal L. Schwartz. So I have seen what I can do with subroutine references. Now I am a subroutine prototyper by nature. In fact I do two things that seem to frustrate some fellow programers but it seems natural to me. I declare my subroutines before using them and prototype them at the same time. There are many reasons to do this, but a few is to catcht programming errors. The main being:
- My variables become pseudo-global because they spill into the subroutine from above. There was some code I was editting recently and I could not figure out where the sub was getting the value from and I had to come through the main programming area to find the variable. To me a sub should be self-contained fully. And declaring them before the program avoids this.
- By prototyping I can use minimal error checking on the values passed to the subroutines.
- I prefer to see the definition of the sub before I see the call to the sub. Just habit I hate reading code and than using find to see the sub at the end. When reading code and the subs are at the top I see what each is doing and have a summary in my mind when I see the call
That said I have had problems with prototypes to anonymous subroutines.
use strict;
my $SubRef = sub (\@$){
my $ArrayRef = shift;
my $Scalar = shift;
foreach my $item (@$ArrayRef){
print "$item";
}
print "\n";
print "$Scalar";
print "\n";
};
my @Array = ("This ", "Is ", "A ", "Test ", ".");
my $Scalar = "That was a test.";
$SubRef->(@Array , $Scalar);
Now this code gives me:
Can't use string ("This ") as an ARRAY ref while "strict refs" in use
+at C:\Projects\test.pl line 5.
Now if I change the code like this:
my $SubRef = sub ($$){
and
$SubRef->(\@Array , $Scalar);
And the output is fine. I can even leave it as:
my $SubRef = (\@$){
As long as I change the call to the sub to have the \@ it works. Am I missing something here or doing something silly. I am probably doing something silly but I can't see it. Any pointers or references would be appreciated. Sorry didn't see the pun in that until posted.
Update:
So would it be better to use anonymous arrays and hashes as a general rule of thumb? It seems to me this would minimise confusion in the subs by making the main body of the program ensure that everything already was a ref before you call the sub. But this might just be the mindset for what I am doing. Thank you all for the information.
"No matter where you go, there you are." BB