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
Today’s Wordle is one of my favorite parts of the day, so it’s a paradox that happiest when we solve the puzzle quickly. My mornings are hectic. Today’s wordle is moderately challenging because of uncertainty. Today’s Wordle took the world by storm when it launched, and has kept players glued to their phone screens ever since.
Thank you for your reasonable criticism. My neighbor and I are preparing to do some research on that temple run. We got a good book about it from our local library and most of the books are not as impactful as your information.
sportbootführerschein binnen und see, sportbootführerschein binnen prüfungsfragen, sportbootführerschein binnen kosten, sportbootführerschein binnen online, sportbootführerschein binnen wo darf ich fahren, sportbootführerschein binnen berlin, sportbootführerschein binnen segel, sportbootführerschein kaufen, sportbootführerschein kaufen erfahrungen, sportbootführerschein kaufen schwarz, sportbootführerschein see kaufen, sportbootführerschein binnen kaufen, sportbootführerschein see kaufen ohne prüfung, bootsführerschein kaufen, bootsführerschein kaufen polen, bootsführerschein kaufen erfahrungen, bootsführerschein online kaufen, bootsführerschein tschechien kaufen. https://sportbootfuhrerscheinkaufen.com/
sportbootführerschein see
I am continually looking online for articles that can facilitate me. Thank you! 토토사이트
I stumbled on this while browsing on google I’ll be sure to come back. thanks for sharing. https://therowdylender.com/
What’s up colleagues, its enormous post regarding educationand entirely defined, keep it up all the time. 메이저사이트
F*ckin¦ Have you ever thought about including a little bit more than just your articles? 먹튀검증
This technique offers valuable flexibility in Bash scripting, but you should choose the approach that best fits your version and coding style. | [url=https://www.mcallendrywall.com]https://www.mcallendrywall.com[/url]
This technique offers valuable flexibility in Bash scripting, but you should choose the approach that best fits your version and coding style.
Monkey Type is an engaging and interactive website that offers educational games, videos, and books for kids of all ages. It covers a wide range of subjects including math, reading, science, and problem-solving. With its entertaining content and educational focus, Funbrain provides a fun learning experience for children while reinforcing key academic skills.
Monkey type
https://www.area-codes.us/347-area-code/
347 Area code is a New York City area code covering the Bronx, Queens, Brooklyn. This area code was assigned on February 19, 1999. It went live on October 1, 1999. 347 Area code is a general purpose code. Service area 347 overlaps with area codes 718 917 929. The dialing pattern for local calls within the same NPA (area code) is 1+10D.
Nerdle, the mathematical marvel of a game! A delight for the brainy bunch who like to flex their mental muscles while having a jolly good time. This charming game involves solving a plethora of mathematical puzzles to guide our little Nerdle through a maze of obstacles. Nerdle Game is the perfect amalgamation of fun and learning, and will leave you feeling satisfied and smarter than ever before. So why not give it a go and see if you can conquer the mathematical marvel that is Nerdle!
I love this information you have written here. It’s insightful and interesting. I will come back for more as soon as I can. Thank you. 토토사이트추천
Thats Good For Who are Searching Something Else For Fun
What a great source of information. Such a wonderful collection of new ideas. I’ll definitely be back! 토토사이트
Thanks for this wonderful post! It has long been very helpful. I wish that you’ll carry on posting your wisdom with us. 토토사이트 I hope more and more people will find such a good article.
It’s a clever way to boost code adaptability and customization.
its me blippi Do you remember B L I P P I.