#!/usr/bin/perl use strict; use warnings; use Data::Dump qw(pp); $| =1; #some advanced stuff to make the printout in the right order #forget about this for now... # a reference to an array is a scalar value.. my $ref2_array_first_run = return_array(1); my $ref2_array_second_run = return_array(4); print "Scalar value of \$ref2_array_first_run is $ref2_array_first_run\n"; pp $ref2_array_first_run; print "Scalar value of \$ref2_array_second_run is $ref2_array_second_run\n"; pp $ref2_array_second_run; my @copy = @$ref2_array_first_run; # copy array to another block of # memory called @copy $ref2_array_first_run = undef; # zap memory that first call to # return_array() allocated. pp $ref2_array_first_run; # memory no long in use! pp \@copy; # A copy of the first run now # exists in other memory sub return_array { my $start_num = shift; #so that each run is different # my @array = (1, 2, 3); my @array = ($start_num..$start_num+2); # Question is whether or not calculate() should modify @array? # If so, here are 2 ways to do that... foreach my $element (@array) { # calculate($element); # does not modify @array! # these 2 calculate methods both modify @array... $element = calculate($element); # most obvious way calculate2 (\$element); # using ref to $element } return \@array; } sub calculate { my $value = shift; return ($value *5); #multiplies by 5 } sub calculate2 { my $ref2scalar = shift; $$ref2scalar *= 10; # multiplies by 10 # no "return value" needed } __END__ Prints: ## This shows that the ARRAY references created by run1 and run2 ## do indeed point to different memory Scalar value of $ref2_array_first_run is ARRAY(0x6c35e0) [50, 100, 150] # "pretty print" output for 1,2,3 Scalar value of $ref2_array_second_run is ARRAY(0xfcb430) [200, 250, 300] # "pretty_print" output for 4,5,6 undef # memory used for the first array creation is GONE. [50, 100, 150] # the @copy of the first run still exists