Mailing List Archive


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

Re: [tlug] Bash looping issue



On Wed, Oct 13, 2010 at 01:37, Romeo Theriault <romeo.theriault@example.com> wrote:
On Wed, Oct 13, 2010 at 00:14, Daniel A. Ramaley <daniel.ramaley@example.com> wrote:
Hello. In the example script below, i define an associative array and
then make a copy of it using a loop to copy each key/value pair. It
seems to work quite nicely... within the loop. Once outside the loop,
the copied array loses its data. The bizarre thing is that if i switch
the loop construct from a "while" to a "for", it works. I'd really like
to use the "while" loop, however, so that in more complicated scripts i
can process the keys in sorted order. (This would be useful, for
example, in building a sorted list of the keys of an associative array.)
I've pasted my sample script and the output below. Any ideas?


Looks like bash is starting the while-read loop in a subshell so you're losing your variable assignments when the subshell exits. This page talks about a few ways around this:

http://fvue.nl/wiki/Bash:_Piped_%60while-read'_loop_starts_subshell


I might also add that perl, and I'm sure countless other languages, are really good at this kind of thing ;) But maybe you need (or really want to) use bash for some reason.

#!/usr/bin/perl -w
use strict;

my %ORIG = ("key 1" => "Y",
            "key 4" => "Z",
            "key 3" => "B",
            "key 2" => "C"
           );

# Copy the whole hash into the new COPY hash.
my %COPY =  %ORIG;

# Print %COPY hash sorted
print "Copy:\n";
foreach my $key (sort keys %COPY) {
        print "$key: $COPY{$key}\n";
}

# Print Orig unsorted
print "\n";
print "Orig:\n";
foreach my $key (keys %ORIG) {
        print "$key: $ORIG{$key}\n";
}


Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links