I have a little script that is running my computer out of memory, and I was wondering if there might be a way around this problem. I have been thinking about it for the last few days and haven't come up with anything. Someone a few days ago mentioned something called forking. I can guess at what that is, but for some reason I get the feeling that forking isn't well liked, but I may be wrong there.
#!/usr/bin/perl -l
use strict;
use warnings;
use feature qw(say);
use List::Util qw(sum max);
use lib 'lib';
use Base::Nifty qw(commify);
say "How many children are in the first generation?";
my $generation = <>;
say "How many generations do you want to generate?";
my $generations = <>;
chomp($generation,$generations);
my %generations = (
1 => $generation,
);
for (1..$generations) {
my @generation;
for (1..$generation) {
my $children = int(rand(6));
push @generation, $children;
}
$generation = sum(@generation);
$generations{$_ + 1} = $generation;
@generation = ();
}
my $max_length_generation = length(commify(max(keys %generations)));
my $max_length_children = length(commify(max(values %generations)));
for (sort {$a <=> $b} keys %generations) {
printf "%${max_length_generation}s: %${max_length_children}s\n",$_,c
+ommify($generations{$_});
}
When I run that with 5 initial children and 20 generations, I run out of memory. 5 and 19 doesn't. I have a feeling that my $children = int(rand(6)); is what is killing my memory when the amount of children in a generation is in the billions. By the way, as with all my scripts, this is just a bit of fun, so I am not in any great rush.
Have a cookie and a very nice day!
Lady Aleena
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|