如何使用间接引用遍历数组?

编程入门 行业动态 更新时间:2024-10-25 03:21:29
本文介绍了如何使用间接引用遍历数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我怎样才能使这段代码工作?

How can I make this code work?

#!/bin/bash ARRAYNAME='FRUITS' FRUITS=( APPLE BANANA ORANGE ) for FRUIT in ${!ARRAYNAME[@]} do echo ${FRUIT} done

此代码:

echo ${!ARRAYNAME[0]}

打印苹果.我正在尝试做类似的事情,但使用[@]"来遍历数组.

Prints APPLE. I'm tryng to do something similar but with "[@]" to iterate over the array.

提前致谢,

推荐答案

${!ARRAYNAME[@]} 的意思是ARRAYNAME 的索引".正如 bash 手册页中所述,因为 ARRAYNAME 已设置,但作为字符串而不是数组,它返回 0.

${!ARRAYNAME[@]} means "the indices of ARRAYNAME". As stated in the bash man page since ARRAYNAME is set, but as a string, not an array, it returns 0.

这是一个使用 eval 的解决方案.

Here's a solution using eval.

#!/usr/bin/env bash ARRAYNAME='FRUITS' FRUITS=( APPLE BANANA ORANGE ) eval array=( ${${ARRAYNAME}[@]} ) for fruit in "${array[@]}"; do echo ${fruit} done

您最初尝试做的是创建一个间接引用.这些是在 bash 版本 2 中引入的,旨在在尝试在 shell 中实现类似反射的行为时在很大程度上取代对 eval 的需求.

What you were originally trying to do was create an Indirect Reference. These were introduced in bash version 2 and were meant to largely replace the need for eval when trying to achieve reflection-like behavior in the shell.

在对数组使用间接引用时,您必须在对变量名称的猜测中包含 [@] :

What you have to do when using indirect references with arrays is include the [@] in your guess at the variable name:

#!/usr/bin/env bash ARRAYNAME='FRUITS' FRUITS=( APPLE BANANA ORANGE ) array="${ARRAYNAME}[@]" for fruit in "${!array}"; do echo $fruit done

综上所述,在这个简单的示例中使用间接引用是一回事,但是,正如 Dennis Williamson 提供的链接中所指出的,您应该对在实际脚本中使用它们犹豫不决.它们几乎肯定会使您的代码比必要的更加混乱.通常,您可以使用关联数组获得所需的功能.

All that said, it's one thing to use Indirect References in this trivial example, but, as indicated in the link provided by Dennis Williamson, you should be hesitant to use them in real-world scripts. They are all but guaranteed to make your code more confusing than necessary. Usually you can get the functionality you need with an Associative Array.

更多推荐

如何使用间接引用遍历数组?

本文发布于:2023-11-04 01:09:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556543.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:遍历   数组   如何使用

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!