配列の"ある列"(数値)でソートするperlスクリプトの例

参考:http://chaichan.web.infoseek.co.jp/src/perl07.htm


たとえば、inputfileの14列目に入っている値をもとにソートしたい場合は、次のような感じ。

#! usr/bin/perl
#
#--------------------------------------------------------------
#
#           sort_chi_square.pl
#
#--------------------------------------------------------------
#
# Description:
# ===========
#		chi_square.cで計算させたカイ2乗の値でデータをソートする
#	ためのperlスクリプト。
#
#
# Usage:
# =====
#	sort_chi_square.pl  inputfile   outputfile
#
#	inputfile	: たぶんtemp.dataとか
#	outputfile	: カイ2乗でソートしたファイル
#
# Revision history:
# ================
#   created   October  21  2007  Ono
#
#--------------------------------------------------------------


if(@ARGV != 2){
	die "usage: sort_chi_square.pl  inputfile   outputfile \n";
}

$inputfile	= shift @ARGV;
$outputfile	= shift @ARGV;

open(IN_FILE, $inputfile) or die "Failed to open $inputfile.\n";
open(OUT_FILE, ">$outputfile") or die "Failed to open $outputfile.\n";

while($tmp = <IN_FILE>){
	chomp $tmp;
	push(@model_data, $tmp);
}

@sorted_data = sort { (split(/\s+/, $a))[13] <=> (split(/\s+/, $b))[13] } @model_data;

for($i=0; $i<@sorted_data; $i++){
	printf OUT_FILE "$sorted_data[$i] \n";
}

close(OUT_FILE);