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:
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:
Now if I change the code like this:Can't use string ("This ") as an ARRAY ref while "strict refs" in use +at C:\Projects\test.pl line 5.
andmy $SubRef = sub ($$){
And the output is fine. I can even leave it as:$SubRef->(\@Array , $Scalar);
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.my $SubRef = (\@$){
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.
In reply to Subroutine References by Ninthwave
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |