[Top][All Lists]

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

Re: Add support for array .pop()

From: konsolebox
Subject: Re: Add support for array .pop()
Date: Sat, 15 Oct 2016 19:32:23 +0800

On Sat, Oct 15, 2016 at 11:12 AM, Marco Ippolito <address@hidden> wrote:
> Bash has elegant and powerful constructs like `mapfile',
> yet it is missing something as easy as an array "pop".
> Extract the last value of an array at the same time as
> removing it from the array.
> Is this the best one can do?
> $ a=(1 2 3); v=${a[-1]}; unset 'a[-1]'; printf '%s\n' "$v" "address@hidden"
> The 2-step approach gets tiresome after a while.
> For positional parameters, it _does_ have `shift'...
> ... maybe it could add a `pop`, somehow?

Since you're using Bash-4.3 (or 4.4), you can create a function that
uses declare -n:

$ function array_pop { declare -n __a=$1; __=${__a[-1]}; unset '__a[-1]'; }
$ a=(1 2 3); array_pop a; printf '%s\n' "$__" "address@hidden"

And my simple rule to using functions that process variables with -n:
don't pass variables that begin with two underscores.  There's another
way to avoid variable name conflicts, and that is to prefix the
reference variables with the name of the function itself, but I find
that already an overkill.

You can also improve the function by adding sanity checks, but that's
the basic concept of it.


reply via email to

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