Una de las grandes ventajas de los lenguajes interpretados es que podemos almacenar en una variable el nombre de otra variable y trabajar con su valor. ¿Punteros? Bueno, al final es parecido a la utilización de punteros en C, aunque aquí podemos hacer referencia por el mismo nombre de la variable incluso, previo filtrado y con mucho cuidado, preguntarle al usuario el de la variable para trabajar con ella.
Esto nos puede dar mucha flexibilidad en nuestro código. Por ejemplo, yo lo he utilizado para perfeccionar mi script de lectura de ficheros de configuración al que le podemos pasar también el nombre de la variable donde almacenar la configuración.
Tabla de contenidos
Arrays con nombre dinámico
En Bash, acceder a una variable cuyo nombre está contenido dentro de otra variable es sencillo, podemos hacerlo llamando a ${!NOMBREDEVARIABLE}. Podemos ver un ejemplo en el post referenciado.
El problema es que cuando son arrays no es tan inmediato. El objetivo es que, teniendo una variable que contiene el nombre del array podamos acceder a su información de una forma sencilla. Y El problema aquí viene en la versión de Bash que estemos utilizando. En este caso debemos hacerlo de una forma u otra dependiendo de si utilizamos una versión inferior a la 4.3 (más o menos salió en 2014) o si tenemos una versión posterior.
Ejemplo para Bash < 4.3
Lo siento, mira que no me gusta utilizar eval, pero claro, para estas versiones del intérprete necesitamos crear una cadena de caracteres con la llamada que vamos a hacer y luego evaluar dicha cadena de caracteres. Esto nos dará el valor que buscamos. Por ejemplo:
1 2 3 4 5 6 | MIARRAY=("cero" "uno" "dos" "tres") REFERENCIA="MIARRAY" # Lo que necesitamos es acceder a cada uno de los elementos de MIARRAY a través de REFERENCIA. eval echo \${$REFERENCIA[2]} |
Si os fijáis, al construir la cadena. El primer símbolo de dólar ($) lo escapamos con la barra para que no se interprete. El que sí tiene que interpretar es el segundo, para que $REFERENCIA se transforme en el nombre del array.
Lo podemos hacer con arrays asociativos también sin problema, pero es algo complicado y realizamos demasiadas tareas para hacer referencia a una variable. Además no queda muy elegante o intuitivo tener que escapar un dólar y otro no.
Ejemplo para Bash >= 4.3
Para estas versiones, disponemos de un modificador en la orden declare (también llamada typeset) a través del cual podemos crear una variable de referencia que se comportará exactamente igual que nuestro array:
1 2 3 4 | MIARRAY=("cero" "uno" "dos" "tres") declare -n REFERENCIA="MIARRAY" echo ${REFERENCIA[2]} |
Además, de esta forma, el nombre de la variable puede venir dado en otra variable, con lo que podemos permitir que el usuario especifique el nombre de variable. Eso sí, con mucho cuidado.
Foto principal: Ruben Ortega
The information you shared is very accurate, it gives me the knowledge that I need to learn. Thank you for sharing this useful information. wordle
Thanks for sharing this article. It is very helpful for us to develop my skills in the right way.Skirts for Girls
Una de las grandes ventajas de shell shockers los lenguajes interpretados es que podemos almacenar en una variable el nombre de otra variable y trabajar con su valor.
Thanks for sharing this article. It is very helpful for us to develop my skills in the right way. Newport roofing
I now have the knowledge I need to study because of the factual information you supplied. I appreciate you giving this insightful information.
Check out online retailers that specialize in beauty supplies. Some popular options include Sally Beauty and Ulta Beauty.
Try searching for nail supply stores on online marketplaces, such as Amazon or eBay.holiday nails
Desde luego que si eres nuevo en esto de la programación, lo de arrays te puede sonar un poco raro, pero, la palabra lista dinosaur game, la tienes a la orden del día.
I love the cover image. It looks so beautiful. exterior painting boston ma
Excellent information on your blog, thank you for taking the time to share with us.
furniture restoration in sydney
This is a fantastic piece of writing. For a writing prompt, this is easily in my top five. The quality and inspiration of your work is just remarkable. You have my gratitude.
build now gg
large number of fast individuals if you want to have the upper hand in scoring attacks. backrooms
I’ve been troubled for several days with this topic. 카지노사이트, But by chance looking at your post solved my problem! I will leave my blog, so when would you like to visit it?
Los websites dan mucho trabajo y tiene sus altos y bajos pero bueno, esto no deja de ser una afición al menos en la mayoría de gente que conozco. Ya se irá llevando cuando y como se pueda david martinez jacket for sale
Even though the features may be very familiar, Bash’s syntax can be challenging 1v1 lol. You will learn how to declare arrays in this tutorial, as well as how to use them in your code.
I found this post to be quite helpful and intriguing. We appreciate you sharing your unique opinions with us. I will most certainly share this with my peers.
connect 4 brain game, game for all ages and genders
This always saves me time and effort when working with arrays in Bash.
It is a good article. I am looking for such type of article and now I got it. Thank you so much.
Quordle is one of the most popular variations of the popular video game Wordle. In this game variation, you must guess four words per day.
Actually, it’s pretty good to see! [url=https://www.topadelaidetiling.com]Tiler Adelaide[/url]
Actually, it’s pretty good to see! Tiler Adelaide
Thanks for sharing! Tiler Adelaide
Thanks for letting us know! Tiler Wollongong
Good to know about this! Tilers Wollongong Oak Flats
Excellent post! Concreters in Wollongong
Thanks for sharing this to public! Adelaide Landscaping
Such a great post! Landscaping Henley Beach
I visited Your blog and got a massive number of informative articles. I read many articles carefully and got the information that I had been looking for for a long time. Hope you will write such a helpful article in future. Thanks for writing.Tilers in Hobart
Very useful and informative post! Tiling Townsville
Thats what I was looking for! Somerton Park Air Conditioning
Very informative post! tiler melbourne
To be honest, I generally don’t read. But, this article caught my attention.seo adelaide
I am really impressed with your writing style. Keep it up! Landscapers Canberra
Many thanks for sharing this! Adelaide Coolroom Hire
Thanks for sharing! Sliding Doors Adelaide
It’s so kind of you! Solar Panels Adelaide
Many many thanks to you! Cleaning Services Adelaide
You presented your ideas and thoughts really well on the paper. Solar Panels Adelaide
What a great piece of article! seo adelaide
Very informative content. Thanks. tow truck wollongong
Please keep up the good work! drum lessons adelaide
Thanks for letting us know. Tiler Adelaide
I thik this is very helpfull post Canberra landscapers
Great Post! I learned a lot from this, Thank you! Canberra landscapers
Really nice article and helpful me Canberra landscapers
Nice article, waiting for your another Canberra landscapers
We from impermeabilizacion de terraza admire what you have done here. I love the part where you say you are doing this to give back but I would assume by all the comments that are working for you as well. Do you have any more info on this?
Además no queda muy elegante o intuitivo tener que escapar un dólar y otro no. home remodeling in dallas texas
The use of dynamically named arrays in Bash can be a powerful tool in the hands of an experienced developer, but it should be used carefully and with proper validation to avoid potential issues.
The «Spacebar Counter» TikTok challenge is a trend where users use a spacebar counter tool or software to measure how many times they can press the spacebar counter.
Coreball is an addictive online video game that you won’t be able to put down! Zigzag your way to high ratings!
Good step you have written of writing content relating to cooperate sense. Better yet good working skills and hope you write more of this soon.The Crowded Room Tom Holland Jacket