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

I am new to using subroutines in perl. I am having a problem getting a subroutine to return an array. If I do something like this:
@net = mask($a,$b); sub mask { <<code>> return @base; }
Shouldn't that return @base to @net?

Retitled by Steve_p from 'subroutines'.

Replies are listed 'Best First'.
Re: Returning arrays from subroutines
by revdiablo (Prior) on Jun 16, 2005 at 22:37 UTC

    It will turn @base into a list containing all of its elements, return that, then on assignment it will create @net from that list. In other words, yes, it will work as you probably are expecting. What happened when you tried it?

      When I tried to print @net it came out as a memory location, similar to ARRAY(0xFFC16), which made me think that it was a reference for some reason.
        similar to ARRAY(0xFFC16), which made me think that it was a reference for some reason

        This thought was correct; that is what happens when you try to print a reference. There's really not much we can do to help you with this part, though, because the code you pasted doesn't create a reference anywhere.

Re: Returning arrays from subroutines
by djohnston (Monk) on Jun 16, 2005 at 23:03 UTC
    Your mask subroutine is basically returning a copy of @base which is then assigned to @net. The technique has some performance issues, but should work fine as long as you only need to return a single list. Things get slightly more complicated when later you find that you need to return some other values from mask.
      And when you get to that point, you'll want to look into passing and returning references rather than the actual arrays. References are scalars that know where an array lives so you can pass a single scalar back and forth, but still access the elements. Check the [id://Tutorials] for some more info (among other places).
Re: Returning arrays from subroutines
by moot (Chaplain) on Jun 16, 2005 at 23:16 UTC
    Also if you're working with netmasks (which it looks like you might be), you might find all that you're trying to do has been been done - look into Net::IP and NetAddr::IP.

    Update: didn't see that 'new to subroutines' bit at first. Carry on, carry on..

      Also Net::Netmask might do the trick...

      .:| If it can't be fixed .. Don't break it |:.

Re: Returning arrays from subroutines
by jZed (Prior) on Jun 16, 2005 at 22:37 UTC
    Yes.