wfsp has asked for the wisdom of the Perl Monks concerning the following question:

I have a sub that calls another sub.
I would like to have the called sub manipulate an array declared in the calling sub.
Below is a simplifed example of what I'm trying to do. The actual code I'm working on is a tk script.

This seems to be very expensive.

#! perl use warnings; use strict; scope_test(); sub scope_test{ my @data_in = <DATA>; my @data_out; for (0..$#data_in){ @data_out = call_back($data_in[$_], @data_out); } print "$_" for @data_out; } sub call_back{ my $element = shift; my @data_out = @_; push @data_out, $element; return @data_out; } __DATA__ line one line two line three

Replies are listed 'Best First'.
Re: Attempt at eliminating a global variable
by ikegami (Patriarch) on Jan 18, 2005 at 18:56 UTC

    Pass a reference to the array:

    call_back(\@data_out, $data_in[$_]); sub call_back{ my ($data_out, $element) = @_; push @$data_out, $element; }

    Alternate syntax:

    call_back(\@data_out, $data_in[$_]); sub call_back{ our @data_out; local *data_out = $_[0]; my $element = $_[1]; push @data_out, $element; }
      Many thanks ikegami.
      Much neater too!

        btw,

        sub scope_test{ my @data_in = <DATA>; my @data_out; for (0..$#data_in){ call_back(\@data_out, $data_in[$_]); } print "$_" for @data_out; }

        can be simplified to

        sub scope_test{ my @data_out; while (<DATA>) { call_back(\@data_out, $_); } print "$_" for @data_out; }

        or even

        sub scope_test{ my @data_out; call_back(\@data_out, $_) while (<DATA>); print "$_" for @data_out; }