Task 1: Self Spammer
Write a program that outputs one word of its own script / source code at random.
A "word" in this context is defined as any continuous sequence of non-whitespace characters separated by whitespace.
Method Explanation
The task belongs to the family of self-referential programs or quines. Instead of recreating its entire source code, the script needs to access its own file content, parse it into whitespace-delimited tokens ("words"), and select one uniformly at random.
In both languages, this can be achieved cleanly:
- Perl: The special variable
$0holds the current program filename. We open the file safely, read line-by-line or slurp the contents, split on\s+, filter out empty strings, and pick an element using$words[ rand @words ]. - Python: We use
__file__oros.path.abspath(__file__)to locate the running script. The content is read with UTF-8 encoding, tokenized using Python's built-instr.split()(which automatically collapses whitespace), and a word is selected viarandom.choice().
Perl Solution
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(Str);
use Test::More;
signature_for get_random_word => (
method => 0,
positional => [ Str, { default => $0 } ],
);
sub get_random_word ( $filename = $0 ) {
open my $fh, '<', $filename or die "Cannot open $filename: $!";
my @words;
while ( my $line = <$fh> ) {
push @words, split( /\s+/, $line );
}
close $fh;
# Filter out empty tokens
@words = grep { length $_ } @words;
my $random_word = $words[ rand @words ];
return $random_word;
}
Python Solution
import os
import random
def get_random_word(filename: str | None = None) -> str:
"""Read source code, tokenize into whitespace-delimited words, and return a random word."""
target_path = filename if filename is not None else os.path.abspath(__file__)
with open(target_path, encoding="utf-8") as file:
content = file.read()
words = content.split()
return random.choice(words) # nosec B311