gregzartman has asked for the wisdom of the Perl Monks concerning the following question:
I am doing some dev for a linux distro with a perl API for managing the configuration for the server. Quite a bit of the underling API are bits of perl code we call event and actions.
One of the "practices" many follow is assigning an empty value when a string is set so as not to end up with a undef value. Something like this:
$var = some_class->some_method() || ''
This is assuming some_method returns a scalar.
I've just always used this approach but found that this doesn't work when returning arrays "some_method" I'm hoping you all can help me understand what perl is doing when it returns and array.
Here's the bit of code I was testing with:
@array1 = get_array2() || (); foreach (@array1) {print "$_\n";} sub get_array2 { @array2 = ("greg","Zartman"); return (@array2); }
I was thinking that @array1 gets assigned @array2 via the get_array2 function unless undef, in which case @array1 get assigned the empty array (). However, I can see from this test code that my thinking is wrong.
Thanks!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Return array from sub or return empty array
by AnomalousMonk (Archbishop) on Jul 04, 2016 at 05:02 UTC | |
|
Re: Return array from sub or return empty array (updated)
by haukex (Archbishop) on Jul 04, 2016 at 06:37 UTC | |
by GrandFather (Saint) on Jul 04, 2016 at 06:54 UTC | |
by gregzartman (Initiate) on Jul 04, 2016 at 18:37 UTC | |
by haukex (Archbishop) on Jul 04, 2016 at 20:09 UTC | |
|
Re: Return array from sub or return empty array
by Anonymous Monk on Jul 04, 2016 at 05:49 UTC | |
|
Re: Return array from sub or return empty array
by Cow1337killr (Monk) on Jul 05, 2016 at 03:28 UTC |