Search code examples
perlfunctionsubroutine

Method construction in perl


I'm really confused on how to make a method in perl. What I would like to do is have a method say
printdoc(%hash). I want to be able to call printdoc(%myhash) and then it use what's in the method to print the information then go back to my code. My use here is that I have several hashes I want to print a certain same way, but instead of having to copy paste the code over an over I would like to just be able to call it instead.


Solution

  • You use the sub keyword:

    sub printdoc {
      my %hash = shift;
      # do whatever
    }
    
    printdoc(%hash)
    

    However, this is suboptimal because %hash will be copied. Rather, passing a reference is better:

    sub printdoc {
      my $hash_ref = shift;
      my %hash = %$hash_ref;
      # do whatever
    }
    
    printdoc(\%hash);
    

    By the way, this is called a "subroutine" or a "function". A "method" is specifically a function on an object - no wonder you were just getting the object-oriented answers. :)