尝试修改不可创建的数组值

时间:2012-09-10 18:40:23

标签: perl

我在perl方面没有经验,我在解决此错误时遇到困难。任何帮助表示赞赏。脚本如下(第40行报告的问题,粗体):

#! /usr/bin/perl

print "Please enter filename (without extension): ";
$input = <>;
chomp ($input);

print "Please enter total no. of sequence in fasta file: ";
$orig_size= <>*2-1;
chomp ($orig_size);

open (INFILE, "$input.fasta") or die "Error opening input file for shuffling!";
open (SHUFFLED, ">"."$input"."_shuffled.fasta") or die "Error creating shuffled output file!";

@array = (0); # Need to initialise 1st element in array1&2 for the shift function
@array2 = (0);
$i = 1;
$index = 0;
$index2 = 0;

while (my @line=<INFILE>){
    while ($i<=$orig_size) { 

    $array[$i] = $line[$index];
    $array[$i]=~ s/(.)\s/$1/seg;

    $index++;
    $array2[$i] = $line[$index];
    $array2[$i]=~ s/(.)\s/$1/seg;

    $i++;
    $index++;
    }
}

my $array = shift (@array); 
**my $array2 = shift (@array2);**
for ($i = $header_size; --$i; ) { 
    my $j = int rand ($i+1);
    next if $i == $j;
    @array[$i,$j] = @array[$j,$i];
    @array2[$i,$j] = @array2[$j,$i];
}

while ($index2<=$header_size) { 
    print SHUFFLED "$array[$index2]\n";
    print SHUFFLED "$array2[$index2]\n";
    $index2++;
}
close(INFILE);
close(SHUFFLED);

1 个答案:

答案 0 :(得分:2)

错误:

Modification of non-creatable array value attempted

正如here所说:

  

你试图使数组值成为spring,而且   下标可能是负数,甚至从数组末尾算起   向后。

让我相信你已经把你的行数计算错了,它指的是这个块:

for ($i = $header_size; --$i; ) { 

意味着你已经把循环拉得太远了,$i变成了负数,超出了数组的大小。它的原因是没有定义$header_size(转换为零)。作为旁注,如果您使用了正确的for循环,则不会存在此问题:

for ($i = $header_size; $i >= 0; $i--) 

或者更好的是,perl风格的循环:

for my $i (0 .. $header_size)

尽管这会以相反的顺序迭代,但在这种情况下无关紧要。

你的代码对我来说有点难以理解,但我认为这个块意味着要对你的数组进行洗牌。为此,最好使用List::Util模块中的shuffle函数。它是perl v5.7.3以来的核心模块。 E.g。

use List::Util qw(shuffle);
...
my @shuffled_indexs = shuffle 0..$#array;
@array  = @array [@shuffled_indexes];
@array2 = @array2[@shuffled_indexes];

值得重复的是,不使用

编写代码
use strict;
use warnings;

确实是一个非常糟糕的主意。它将允许无声错误和拼写错误,这将使您的调试变得更加困难。

相关问题