Zeus Odin wrote:
>
> When you loop through an array
>
> for(@array){ ... }
>
> should not each array element be aliased into $_: if you change $_, you
> also change the element?
Yes, that is correct.
> This is what I remembered. However, a problem I
> just encountered shook this recollection.
>
> I think I read somewhere that you should NOT delete array elements from
> within a loop. However, the following works very well.
I think that you are thinking of hashes.
Found in /usr/lib/perl5/5.6.0/pod/perlfaq4.pod
What happens if I add or remove keys from a hash while
iterating over it?
Don't do that. :-)
> The problem is that the current directory (/tmp) can contain multiple
> mosfet*.tar.gz archives and multiple mosfet* directories. The following
> code attempts to leave only alphabetized directories in @dir.
>
> --------------------FIRST TRY------------------------------
> @dir = `ls mosfet* | grep ^mosfet`;
You don't have to call ls and grep to do this:
my @dir = glob 'mosfet*';
> $x=0;
> for (@dir){
> # Remove each array element that is NOT a directory name
> # OR remove ":\s+" from the end of dir name.
> if ( s/^(.*):\s+$/$1/ ){
> $dir[$x] = $_; # substitution changes $_ but not @dir
> } else { # shouldn't the substitution change both?
It does change both:
$ perl -e'
my @dir = ( "mosfet-1.2.3.tar.gz", "mosfet-new: " );
print "@dir\n";
for ( @dir ) {
s/^(.*):\s+$/$1/;
}
print "@dir\n";
'
mosfet-1.2.3.tar.gz mosfet-new:
mosfet-1.2.3.tar.gz mosfet-new
> splice @dir, $x, 1;
> $_ = $dir[$x]; # splice changes @dir but not $_
> redo;
> }
> $x++;
> }
>
> --------------------SECOND TRY-----------------------------
> START: @dir = `ls mosfet* | grep ^mosfet`;
> $x=0;
> for (@dir){ # substitution now changes @dir but NOT $_
> unless( $dir[$x] =~ s/^(.*):\s+$/$1/ ){
> splice @dir, $x, 1;
> $_ = $dir[$x];
> redo;
> }
> $x++;
> }
According to your actual problem:
> The problem is that the current directory (/tmp) can contain multiple
> mosfet*.tar.gz archives and multiple mosfet* directories. The following
> code attempts to leave only alphabetized directories in @dir.
You should do this to get only directories in @dir:
my @dir = grep -d, glob 'mosfet*';
John
--
use Perl;
program
fulfillment
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]