1

I want to initialize 4^9 (=262144) indices of @clump as 0. So I wrote this:

my $k=9;
my @clump=();
my $n=4**$k;
for(my $i=0;$i<$n;$i++){
   push(@clump,0);
   print "$i ";
}

But it keeps freezing at 261632! I then tried making $n=5^9 (=1953125) and my code stopped at 1952392. So its definitely not a memory issue. This should be simple enough but I can't figure out what's wrong with my code. Help a newbie?

5
  • Works fine here: perl -E '$k=9; @clump=(); $n=4**$k; for($i=0;$i<$n;$i++){ push(@clump,0)}' Commented Jul 29, 2015 at 21:53
  • Works for me, as well. Does @clump = (0) x 4 ** $k work for you? Commented Jul 29, 2015 at 21:58
  • 4
    Out of curiosity, what are you trying to do with 4^9 zeros? Commented Jul 29, 2015 at 22:15
  • @Jim Davis -- @clump=(0)x 4**$k worked! Thank you so much. Commented Sep 18, 2015 at 17:25
  • @ThisSuitIsBlackNot I'm writing a clump finding program using frequency arrays to find the ori site in Ecoli genome. For that I need to find the most frequent 9-nucleotide sequences in a genome file. The easiest way was to convert all possible sequences into corresponding array indices and +1 whenever the program encounters the sequence. Commented Sep 18, 2015 at 17:34

2 Answers 2

9

Suffering from buffering?

When I add a sleep 1000 to the end of your program, stream the output to a file, and read the tail of the file, I also observe the last numbers to be printed are 261632 and 1952392. The remaining output is stuck in the output buffer, waiting for some event (the buffer filling up, the filehandle closing, the program exiting, or an explicit flush call) to flush the output.

The buffering can be changed by one of the following statements early in your program

$|= 1;
STDOUT->autoflush(1);

Sign up to request clarification or add additional context in comments.

1 Comment

Of course, rather than flushing after every a couple of characters, one might want to just use print "\n"; after the loop, or use IO::Handle; ... STDOUT->flush.
3
#!/usr/bin/env perl

use strict;
use warnings;

my $k = 9;
my $n = 4 ** $k;
my @clump = (0) x $n;

print join(' ', @clump), "\n";
printf "%d elements in \@clump\n", scalar @clump;

Or,

#!/usr/bin/env perl

use strict;
use warnings;

my $k = 9;
my $n = 4 ** $k;
my @clump;
$#clump = $n - 1;
$_ = 0 for @clump;

print join(' ', @clump), "\n";
printf "%d elements in \@clump\n", scalar @clump;

Output:

... 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
262144 elements in @clump

Also, note that initialization with 0 is almost never required in Perl. Why do you need this?

1 Comment

Your first suggestion worked. Thank you for your help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.