I am having trouble trying to pass a hash as an argument to a module. Ultimately I want to use the hash as an index of column names, but for this post I'll just use toy code. I haven't written a module before and have been following this webpage for guidance:
https://www.perl.com/article/25/2013/5/20/Old-School-Object-Oriented-Perl/
My module code is:And my code to call the module is:1 package toy_module; 2 3 sub new { 4 my ($class, $args) = @_; 5 my $self = { 6 simple_hash => $args->{simple_hash}, 7 simple_test_scalar => $args->{simple_test_scalar}, 8 }; 9 print "********** INSIDE SUBROUTINE NEW **********\n"; 10 print "simple scalar: ".$self->{simple_test_scalar}."\n"; 11 print "$_\n" for keys %$self->{simple_hash}; 12 return bless $self, $class; 13 } 14 15 sub show_simple_hash { 16 my $self = shift; 17 print "********** INSIDE SUBROUTINE SHOW_SIMPLE_HASH ***** +*****\n"; 18 print "simple scalar: ".$self->{simple_test_scalar}."\n"; 19 print "$_\n" for keys %$self->{simple_hash}; 20 } 21 22 1;
What I hoped to see was the little_test_hash being passed along (and its keys printed) when test_object is instantiated by the subroutine "new", and then to see it preserved as an attribute (and its keys printed) when the subroutine "show_simple_hash" is called. Instead, this is what I get:1 use strict; 2 use warnings; 3 use lib '~/working/toys'; 4 use toy_module; 5 6 my %little_test_hash = ( 7 COL_1 => 0, 8 COL_2 => 1, 9 COL_3 => 2, 10 COL_4 => 3, 11 COL_5 => 4, 12 ); 13 my $little_test_hash_ref = %little_test_hash; 14 15 my $test_object = toy_module->new({simple_hash=>$little_test_hash_ +ref, simple_test_scalar=>5}); 16 my $next_test = $test_object->show_simple_hash;
Can anyone help me understand what I'm doing wrong?MacBook-Pro:toys mcrepeau$ perl test_toy_module.pl Using a hash as a reference is deprecated at toy_module.pm line 11. Using a hash as a reference is deprecated at toy_module.pm line 19. ********** INSIDE SUBROUTINE NEW ********** simple scalar: 5 Type of argument to keys on reference must be unblessed hashref or arr +ayref at toy_module.pm line 11.
In reply to Trouble passing a hash to a module by mcrepeau
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |