###前提・実現したいこと
大変恐縮ではございますがお答えいただけると幸いです。
perlの基本操作を練習中です。
split関数がうまく使えないので質問しました。
具体的には2種類の種名をファイルから読み込んで分類するプログラムを実行しようとした際うまく行かず、どうやら二つの配列に要素が分割され、入力されていないのが原因のようです。
###発生している問題・エラーメッセージ
perl practice_ref_common.pl siritori_words.txt リンゴ ゴリラ ラッパ パンツ ツミキ キツネ ネズミ ミミズ キツネ ラッパ ゴリラ ランプ ズンダ ダンゴ ゴング グンテ common species only in the first group リンゴ ゴリラ ラッパ パンツ ツミキ キツネ ネズミ ミミズ キツネ ラッパ ゴリラ ランプ ズンダ ダンゴ ゴング グンテ only in the second group
###該当のソースコード
perl
1ファイル名:practice_ref_common.pl 2@species1 = (); 3@species2 = (); 4 5#ファイルから読み込み 6while ($line = <>) { 7 8 chomp $line; 9 ($sp1, $sp2) = split (/\s+/, $line); 10 print $sp1, "\n"; #ここで問題発覚 11 push @species1, $sp1; 12 push @species2, $sp2; 13} 14 15 16($ref_common, $ref_only_in1, $ref_only_in2) = &find_common(\@species1, \@species2); 17 18print "common species\n"; 19foreach $sp (@$ref_common) { 20 print $sp, "\n"; 21} 22print "\n"; 23 24print "only in the first group\n"; 25foreach $sp (@$ref_only_in1) { 26 print $sp, "\n" 27} 28 29print "\n"; 30 31print "only in the second group\n"; 32foreach $sp (@$ref_only_in2) { 33 print $sp, "\n"; 34} 35 36sub find_common 37{ 38 my ($ref1, $ref2) = @_; 39 40 my @common = (); 41 my @only_in1 = (); 42 my @only_in2 = (); 43 44 my $found; 45 46 foreach my $sp1 (@$ref1) { 47 foreach my $sp2 (@$ref2) { 48 $found = 0; 49 if ($sp1 eq $sp2) { 50 $found = 1; 51 last; 52 } 53 } 54 55 if ($found == 1) { 56 push @common, $sp1; 57 } 58 else { 59 push @only_in1, $sp1; 60 } 61 } 62 63 foreach my $sp2 (@$ref2) { 64 foreach my $sp_common (@common) { 65 $found = 0; 66 if ($sp2 eq $sp_common) { 67 $found = 1; 68 last; 69 } 70 } 71 if ($found == 0) { 72 push @only_in2, $sp2; 73 } 74 } 75 76 return (\@common, \@only_in1, \@only_in2); 77} 78 79読み込みファイル:siritori_words.txt 80リンゴ ゴリラ 81ラッパ パンツ 82ツミキ キツネ 83ネズミ ミミズ 84キツネ ラッパ 85ゴリラ ランプ 86ズンダ ダンゴ 87ゴング グンテ
###試したこと
上記の通りです。
###補足情報(言語/FW/ツール等のバージョンなど)
より詳細な情報
回答1件
あなたの回答
tips
プレビュー