[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: efficient way to use matched string in variable substitution
From: |
Greg Wooledge |
Subject: |
Re: efficient way to use matched string in variable substitution |
Date: |
Tue, 24 Aug 2021 10:32:46 -0400 |
On Tue, Aug 24, 2021 at 04:16:46PM +0200, Léa Gris wrote:
> string2array() {
> # Splits the string's characters into the array
> # $1: The input string
> # $2: The output array name
> [[ "$1" =~ ${1//?/(.)} ]]
> # shellcheck disable=SC2178 # shellcheck broken nameref type check
> local -n arr="$2"
> # shellcheck disable=SC2034 # shellcheck broken nameref usage check
> arr=("${BASH_REMATCH[@]:1}")
> }
Be careful with namerefs used to pass variables by reference. They're
evaluated using the same dynamic scope rules as any other local variable.
If the caller of your function uses "arr" as the second argument, they'll
get an error.
The only strategy I've found to deal with this is to choose ugly local
variable names in any function that uses this approach. E.g. instead
of "arr", you might call your variable "_string2array_arr". Anything
that the caller is unlikely to use, or which you reserve for this purpose
as part of some documented API for your functions, should work.
- Re: efficient way to use matched string in variable substitution, (continued)
- Re: efficient way to use matched string in variable substitution, Greg Wooledge, 2021/08/23
- Re: efficient way to use matched string in variable substitution, L A Walsh, 2021/08/23
- Re: efficient way to use matched string in variable substitution, Greg Wooledge, 2021/08/23
- Re: efficient way to use matched string in variable substitution, Léa Gris, 2021/08/24
- Re: efficient way to use matched string in variable substitution, Greg Wooledge, 2021/08/24
- Re: efficient way to use matched string in variable substitution, Léa Gris, 2021/08/24
- Re: efficient way to use matched string in variable substitution, Mike Jonkmans, 2021/08/24
- Re: efficient way to use matched string in variable substitution, Greg Wooledge, 2021/08/24
- Re: efficient way to use matched string in variable substitution, Mike Jonkmans, 2021/08/24
- Re: efficient way to use matched string in variable substitution, Léa Gris, 2021/08/24
- Re: efficient way to use matched string in variable substitution,
Greg Wooledge <=
- Re: efficient way to use matched string in variable substitution, Mike Jonkmans, 2021/08/24
- Re: efficient way to use matched string in variable substitution, L A Walsh, 2021/08/24
- Re: efficient way to use matched string in variable substitution, Koichi Murase, 2021/08/24
Re: efficient way to use matched string in variable substitution, Oğuz, 2021/08/23