perlの複数の配列をこんな風に並び替えたいんです
@aaa(要素数2) @bbb(要素数2) @ccc(要素数3) @ddd(要素数4) とあった場合
@aaaの先頭、@bbbの先頭、@cccの先頭、@dddの先頭、 @aaaの2番目、@bbbの2番目、@cccの2番目、@dddの2番目、 @cccの3番目、@dddの3番目、@dddの4番目
というような感じで並べ替えたい。 さぁ、どうしたらいいのかな。
package Sort; use strict; use warnings; sub sort { my @sorted; my $total = 0; for my $item(@_){ $total = $total + scalar(@$item); } until( $total == scalar @sorted){ foreach (@_) { if (my $hit = shift (@$_)){ push @sorted , $hit; } } } return @sorted; } 1;
こんな感じで実装してみました。
use Test::More; use Sort; my $aaa = [1,3]; my $bbb = [1,3]; my $ccc = [1,3,5]; my $ddd = [1,3,4,8]; my @expected = ( 1,1,1,1,3,3,3,3,5,4,8); is(Sort::sort ($aaa,$bbb,$ccc,$ddd), @expected, "sort 4 list"); is(Sort::sort ([],[]), (), "sort 2 list empty"); done_testing;
# Failed test 'sort 2 list empty' # at ./t/test.t line 12. # got: '0' # expected: undef
でも、2番目のテストでこけた。 うーん。テストの使い方が今一なんだとおもうのだけど、 空のリストを返しているんだとは思うんだけど 0となってしまいました。
(帰ってきたネコブログ)http://www.nekonotechno.com/nekopress/?p=4619 で言及していただき。テストを書き換えてみました。 かなりすっきりした形になりました。 単純スカラー以外の返却値の関数を作ったら、 リファレンスにして、ディープにテストしないといけませんね。 ほんと初心者丸出し・・・ まぁ、のんびり行きましょう。
use Test::More; use Sort; my @result =Sort::sort ([1,3],[1,3],[1,3,5],[1,3,4,8]); is_deeply(\@result, [ 1,1,1,1,3,3,3,3,5,4,8], "sort 4 list"); @result = Sort::sort ([],[]); is_deeply( \@result, [], "sort 2 list empty"); @result = Sort::sort ([0],[0]); is_deeply( \@result, [0,0], "sort 2 list zero"); done_testing;