bug-bash
[Top][All Lists]
Advanced

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

Re: Stumped on a question of scoping and unset.


From: Steven W. Orr
Subject: Re: Stumped on a question of scoping and unset.
Date: Thu, 26 May 2011 09:11:23 -0400
User-agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.17) Gecko/20110414 Thunderbird/3.1.10

On 5/26/2011 8:18 AM, Greg Wooledge wrote:
On Wed, May 25, 2011 at 05:15:28PM -0400, Steven W. Orr wrote:
In addition, I wrote (what I thought was pretty clever) a function
called glob_array:

glob_array()
{
  [[ snip ]]
     while (( $# ))
     do
         arrayname=$1
         pattern="$2"
         aval=( $pattern )

Looks like what it's trying to do is:

   glob_array arrayname '*.txt'   # equivalent to arrayname=(*.txt)

Right?  (I mean, we have to guess, because you didn't tell us what it's
trying to do.)  So why not simply do:

   arrayname=(*.txt)

and be done with it?  Then you wouldn've have wasted hours and hours
on this nightmarish contraption from hell.

Umm, because glob_array takes a variable name as a reference parameter. Total time consumed so far is under an hour.

typeset -a list_of_blorfs
pattern='*.blorf'
glob_array list_of_blorfs "$pattern"
(( ${#list_of_blorfs[@]} == 0 )) && echo 'Bad news. We have no blorfs.'

I did find that the problem was occurring because I needed to call it differently: The fix (so far) is to do this:

    while (( $# ))
    do
        # arrayname=$1 DONT DO THIS
        typeset $1
        pattern="$2"
        aval=( $pattern )
        nn=${#aval[@]}
        # This should never fail as long as $nn matches passing all of aval.
        # Check anyways for extra credit.
        upvars -a$nn $1 "${aval[@]}" || die "ERROR:upvars failed."

Not a nightmarish contraption from hell at all. In fact, I am managing 10s of thousands of lines of highly modular bash code, and the ability to use uplevel reference parameters is a huge factor in my ability to simplify what otherwise would be about an order more of complexity.

Having said that, the link I referenced:

http://fvue.nl/wiki/Bash:_Passing_variables_by_reference

actually likes using this construct instead:

typeset $1 && upvars -a$nn $1 "${aval[@]}"

The implication seems to be that the typeset command can fail. Is this a reasonable thing to worry about?


--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net



reply via email to

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