Shiping Wang wrote:

[snip]

>>
>>#--
>>#-- header
>>#--
>>print join("\t",(split /\s+/,$line)[EMAIL PROTECTED]@c}]),"\n"; # Although I can 
>>guess
>>this piece of code do the sorting then print out, but don't quite
>>understand how it works, especially [EMAIL PROTECTED]@c}].

no sorting is happening in this line, the sorting is done above it and only 
once. here is the originally code and explanation:

my $j = 0;

#--
#-- here we are building a hash %i that look like:
#--
#-- $i{1} = 0; #-- column 1 should become column 1
#-- $i{4} = 1; #-- column 2 should become column 4
#-- $i{5} = 2; #-- column 3 should become column 5 
#-- $i{2} = 3; #-- column 4 should become column 2
#-- $i{6} = 4; #-- column 5 should become column 6
#-- $i{3} = 5; #-- column 6 should become column 3
#--
my %i = map{$_ => $j++} grep $_, split(/\D+/,my $line = <DATA>);

#--
#-- here we are building an array @c that look like:
#--
#-- $c[0] = 1;
#-- $c[1] = 2;
#-- $c[2] = 3;
#-- $c[3] = 4;
#-- $c[4] = 5;
#-- $c[5] = 6;
#--
#-- you don't really need this @c array
#--
my @c = sort {$a <=> $b} keys %i;
 
#--
#-- header
#--
print join("\t",(split /\s+/,$line)[EMAIL PROTECTED]@c}]),"\n";

#--
#-- @i{...} is called a hash slice in Perl. @c expands to:
#--
#-- (1,2,3,4,5,6);
#--
#-- @[EMAIL PROTECTED] then become:
#--
#-- @i{1,2,3,4,5,6}
#--
#-- which is translated into:
#--
#-- ($i{1},$i{2},$i{3},$i{4},$i{5},$i{6});
#--
#-- which is then translated into:
#--
#-- (0,3,5,1,2,4);
#--
#-- finally:
#--
#-- (split /\s+/,$line)[0,3,5,1,2,4]
#--
#-- created an annoy. list which we then immediately
#-- extract in this order. this is the right order
#-- for your data file.
#--
 
#--
#-- the rest
#--
while(<DATA>){

        #--
        #-- same thing as above
        #--
        print join("\t",(split)[EMAIL PROTECTED]@c}]),"\n";
}

__END__
 
> perl automatically sort array before printing?

no. if you need to sort it, you need to sort it manually. Perl does not sort 
the array for you before printing.

david
-- 
sub'_{print"@_ ";* \ = * __ ,\ & \}
sub'__{print"@_ ";* \ = * ___ ,\ & \}
sub'___{print"@_ ";* \ = * ____ ,\ & \}
sub'____{print"@_,\n"}&{_+Just}(another)->(Perl)->(Hacker)

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to