in reply to Re: Accessing single element without args
in thread Accesing single element without args

The problem here is i can't modify interface_control. It is a global sub which is accessed by many users

@r, has list of routers r[0]....rn, . I want to display output only for r[0] and not for other router

If u see the below code ( under sub interface_control), i want to print blah only for r[0]. If i call interface_control($s), it may end up printing for all routers

foreach my $rh (@r) { print ("blah blah");

Replies are listed 'Best First'.
Re^3: Accessing single element without args
by Athanasius (Archbishop) on Mar 31, 2015 at 04:02 UTC

    Here is one (inelegant) approach which might work for you:

    #! perl use strict; use warnings; use Capture::Tiny ':all'; my ($stdout, $stderr, @result) = capture { interface_control(); }; my @lines = split "\n", $stdout; print $lines[0], "\n"; sub interface_control { my @r; get_handles(\@r); print "blah blah for $_\n" for @r; } sub get_handles { @{ $_[0] } = 11 .. 13; }

    Output:

    14:00 >perl 1204_SoPW.pl blah blah for 11 14:00 >

    Update: Removed unnecessary parentheses from print statement, plus a blank line.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      That makes sense :). I will try to use it if my code reviewer approves :)

      A final query on my question. As i want to print only r[0], is there a way to set the array @r to only r[0] during interface_control call

      . I mean like this
      push (@r, $r[0])

      I know inside interface_control sub, i can set this, but interface_control can call from outside set this value ?

        No. Your original post shows that @r is created as a lexical variable within sub interface_control. So, even if you could somehow access @r from outside the sub, you would have to do so either:

        • before the sub is called; in which case any changes you made would be overriden within the sub before the print statement is reached; or
        • after the sub returns; in which case any changes you made (to a now non-existent variable!) would be too late to affect the printing behaviour.

        I’m not familiar with PadWalker, but following Anonymous Monk’s comment above, I had a quick look. As I understand it, PadWalker allows you to access variables in subroutines higher than your current position in the call stack. As you want to access a variable within a subroutine you will be calling, this module won’t help you either. :-(

        Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re^3: Accessing single element without args
by Anonymous Monk on Mar 31, 2015 at 03:49 UTC

    Well, then there is nothing you can do, short of doing something foolish like using PadWalker