call sub with hash args


/ Published in: Perl
Save to your folder(s)

Use anonymous hash to keep arguments to a sub sane


Copy this code and paste it in your HTML
  1. #!perl
  2. use strict; use warnings;
  3. use Data::Dumper;
  4.  
  5. my @a = (16, 32);
  6.  
  7. #call main
  8. main();
  9. #program execution stops here
  10.  
  11. #subroutine main
  12. sub main {
  13.  
  14. #call subroutine "function1" with a hash as args
  15. function1(
  16. arg1 => 'foo',
  17. arg2 => 'bar',
  18. arg3 => \@a,
  19. );
  20. }
  21.  
  22. sub function1 {
  23. my (%args) = @_;
  24. #define the output record separator and the array separator for printing
  25. local ($\, $,) = ("\n", ', ');
  26.  
  27. #can be used in strings without spaces
  28. print "$args{arg1} baz$args{arg2}";
  29.  
  30. #sometimes the inline dereferences get ugly, so you can deref to a var if you want
  31. print "deref3: " . ($args{arg3}[1] - $args{arg3}[0]);
  32. my @ref3 = @{$args{arg3}};
  33. print "ref3 " . ($ref3[1] - $ref3[0]);
  34.  
  35. #use Data Dumper (core module) to print everything. Can be evaled in from a file to recreate struct
  36. print Dumper( \%args );
  37. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.