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

I have a subroutine as follows

################## sub sample { ################## my $t = shift; my ($p, @r, $v, $rt); $t->get_handles(params=>\$p, rtrs=>\@r, vars=>\$v, t=>\$rt); my @subs; foreach my $rh (@r) { <some command at execution> }

Here, @r takes values which is defined in a file, which is pre-defined, @r always inputs from $r[0]..$r5 .Users can't modify this file or this sub sample. They can only access from their own sub/file

I am calling this sub via another file, but i need @r to process only $r[0]. Is there a way to statically set @r to a single value say, $r[0] ,temporarily from the calling file/sub

Replies are listed 'Best First'.
Re: setting values inside subroutine
by BillKSmith (Monsignor) on Sep 16, 2015 at 13:10 UTC
    The sub get_handles gets the required values. You could modify it. It appears to be a method of object $t. If so, a better approach is to override that method in a new subclass. Only $t objects created in the new subclass would use the new method.
    Bill
Re: setting values inside subroutine
by tangent (Parson) on Sep 16, 2015 at 12:20 UTC
    You say users can't modify this sub, but I take it you can, so you could pass an optional index value to your sub:
    sample($t,0); sub sample { my $t = shift; my $index = shift; my ($p, @r, $v, $rt); $t->get_handles(params=>\$p, rtrs=>\@r, vars=>\$v, t=>\$rt); my @subs; if (defined $index) { my $rh = $r[$index]; <some command at execution> } else { foreach my $rh (@r) { <some command at execution> ... } } }

      Thanks.But, i don't have control over sub SAMPLE. I CAN'T touch it. The problem is, there are around 100 sub's like SAMPLE, which do not have the flexibility as per my ask

Re: setting values inside subroutine
by Anonymous Monk on Sep 16, 2015 at 11:30 UTC

    BTW, i call the sub from my file like this, sample($t);

Re: setting values inside subroutine
by Anonymous Monk on Sep 18, 2015 at 15:15 UTC

    can i make @r an optional argument (reference) and call sample { my ($t, $r_ref) = @_; my @r; @r //= @{$r_ref} .. } # from my own sub?

      yes, just try it ... no need to expand into @r its easy to  $r_ref->[0]

        I called sample from my own sub like this, with the intention of accessing 0th element of @r defined in sample.Its not working. Can you let me know, what is missing here

        sub temp { sample(($t,$r_ref) = @_ ; $r_ref->[0]); }