#!/usr/bin/perl
use strict;
use warnings;
sub paragraph
{
open my $file, "<", "dict.txt" or die "$!";
my @words = <$file>;
close $file;
print "Number of lines:";
my $lines = <>;
print "Max words per line:";
my $range = <>;
for(my $i = 0; $i<$lines; $i++){
my $wordcount = int(rand($range));
for(my $s = 0; $s<=$wordcount; $s++){
my $range2 = scalar(@words);
my $word = int(rand($range2));
print $words[$word]." ";
if($s==$wordcount){
print "\n";}
}
}
}
paragraph;
I’m trying to learn programming, so I just wrote this simple script.
When running this code, I am getting use of uninitialized value errors… I can’t figure out why, but I sure I am just overlooking something.
These two lines open the dict.txt file for writing and then try to read from it.
Since you can’t read from a write-only file, it fails. If the file was writable, then it is empty now – sorry about your nice word list. Suggestion:
Also, please learn to indent your braces in an orthodox fashion, such as:
Also leave a space between ‘if’ or ‘for’ and the open parenthesis.
Your assignment
if ($s = $wordcount)probably isn’t what you intended; however, the conditionif ($s == $wordcount)will always be false since it is in the scope of a loop with the condition$s < $wordcount. You need to rethink that part of your logic.On average, you should choose a better name for your function than
go. Also, it is probably better to invoke it asgo();.When I test compile your script, Perl warns about:
You should fix such errors before posting.
You have:
Unless you have more than 23,496 words in your dictionary, you will likely be accessing an uninitialized word. You should probably use:
That then just leaves you with some logic problems to resolve.
Given ‘dict.txt’ containing:
And ‘xx.pl’ containing:
When I run it, I get: