Created
April 23, 2011 17:27
-
-
Save trapd00r/938801 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
# First off. Always use strict and warnings. | |
# There are places where you cant use strict or warnings, but you'll disable | |
# only a small part of it, like so: | |
# no strict 'refs'; | |
# But you wont have to do that in some time. | |
# So let's add strict and warnings: | |
use strict; | |
# I prefer to make all my warnings fatal. That means, if you get a warning, it | |
# will count as a compile time error, and the script will terminate. | |
use warnings FATAL => 'all'; | |
# Those are global! That's very rarely needed, and when it's needed, you should | |
# prefix them with our, like so: | |
# our @words; | |
# Elsewhere, always prefix them with my. That'll make it *lexical* to the current | |
# scope. Very important. | |
# Also, he creates an array with ONE element here. That's not what he wanted. | |
# He meant: | |
# @words = () | |
# That'll give the array @words the value of an empty list. But that is never | |
# needed when you're initializing an array, because it's always empty. | |
# So we replace this: | |
## @words = (""); | |
## $counter = 0; | |
# with this... | |
my @words; | |
my $counter = 0; | |
# Once again - use lexicals! What he does here is using barewords, words without | |
# sigills. Those are globals - bad. | |
# So we replace this.. | |
## open FILE, "<words.dta" or die $!; | |
## while ($line = readline(FILE)) | |
## { | |
## chomp $line; | |
## push(@words, $line); | |
## $counter++; | |
## } | |
## close(FILE); | |
# with this... | |
open(my $fh, '<', 'words.dta') or die("Cant open words.dta: $!\n"); | |
while(my $line = <$fh>) { | |
chomp $line; | |
push(@words, $line); | |
$counter++; | |
} | |
close $fh; | |
# choose one | |
$random_number = int(rand($counter)); | |
print $words[$random_number] . "\n"; | |
# Furthermore, there's no need for that counter. You get the number of elements | |
# of a list by using it in scalar context, so: | |
print $words[ int(rand( @words )) ], "\n"; | |
# would suffer well. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment