faqts : Computers : Programming : Languages : Perl : Common Problems : Subroutines

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

7 of 15 people (47%) answered Yes
Recently 4 of 10 people (40%) answered Yes

Entry

How do I pass a structure by reference and then access its elements in a sub-routine?
How do I de-reference a structure within a sub-routine?

Jul 15th, 2001 02:55
Per M Knutsen,


The following example illustrates creation by a hash of an array, the 
passing of the hash to a sub-routine by reference, and then de-
referencing of the structure within the routine. Pay notice to the 
curly-brackets and declaration of data-types (array in this case). 
Explore the example by adding your own arrays or hashes to %myHash, and 
then de-reference and process these within the sub-routine!
#!/usr/bin/perl
use strict;
use warnings;
# Create array
my @names = ["Rick","Ray","Charles"];
# Create hash
my %myHash = ( "names" => @names );
# Call sub-routine and pass hash by reference
printNames(\%myHash);
# Sub-routine for printing names
sub printNames {
    my ($hashRef) = @_;   # hashRef now contains the reference to your 
hash
    my ($name);
    # Next, de-reference hashRef and declare the names key an array 
    foreach $name ( @{ $hashRef->{"names"} } ) {
	print $name."\n";
    }
}