help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Passing multiple arrays to a function


From: Greg Wooledge
Subject: Re: [Help-bash] Passing multiple arrays to a function
Date: Tue, 19 Feb 2019 09:11:09 -0500
User-agent: NeoMutt/20170113 (1.7.2)

On Fri, Feb 15, 2019 at 06:44:13AM +0300, Dmitry Alexandrov wrote:
> This is perfectly possible with namerefs as well:
> 

> #!/bin/bash
> 
> array_1=("PASS")
> array_2=("1 foo" "2 foo")
> 
> nameref-safe-fn ()
> {
>     local -n a_ref=$1 b_ref=$2
>     local a=("address@hidden") b=("address@hidden")
>     local array_1=('FAIL')
>     printf '%s;' "address@hidden" "address@hidden"
>     printf '\n'
> }
> 
> nameref-safe-fn array_1 array_2

wooledg:~$ a_ref=(x y z) b=(q w e)
wooledg:~$ nameref-safe-fn a_ref b
bash-5.0: local: warning: a_ref: circular name reference
bash-5.0: warning: a_ref: circular name reference
bash-5.0: warning: a_ref: circular name reference
bash-5.0: warning: a_ref: circular name reference
x;y;z;q;w;e;

I... guess... maybe?  If you ignore all the warnings?  In bash 5.0 only,
of course.

In bash 4.4, you get:

wooledg:~$ a_ref=(x y z) b=(q w e)
wooledg:~$ nameref-safe-fn a_ref b
bash: local: warning: a_ref: circular name reference
bash: warning: a_ref: circular name reference
bash: warning: a_ref: circular name reference
q;w;e;

Also, this function makes a full local copy of each array for no
apparent reason.  One of the main reasons people want to pass an array by
reference to a function (especially one which doesn't modify the array)
is to avoid having to copy each and every element.

Here's a simpler version:

wooledg:~$ print2arrays() {
> local -n __p2a1=$1 __p2a2=$2
> printf '%s;' "address@hidden" "address@hidden"
> echo
> }
wooledg:~$ print2arrays a_ref b
x;y;z;q;w;e;

Of course, this still suffers from the fundamental problem that if the
caller goes out of their way to use __p2a1 or __p2a2 as one of their array
names and passes it to this function, things will blow up.  By choosing
something ugly and with the function's own name (sort of) embedded inside
it, one can try to minimize the chances of this happening accidentally.
You can't prevent a sufficiently clever and self-destructive user from
shooting themselves in the foot, though.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]