#!/usr/bin/perl -w use 5.004; use strict; use Getopt::Std; srand($$ ^ time); # get the options: my %opts; usage() unless (getopts('t:i:o:h', \%opts)); usage() if ($opts{'h'} || !$opts{'t'}); # the opening and closing tags we'll insert into the text: my $opening_tag = "<$opts{'t'}>"; my $closing_tag = ""; # open the input file for reading, or, if no file was specified, get some text # from the console: my $text_from_console; if ($opts{'i'}) { open(INFILE, "< $opts{'i'}") || die "Couldn't open file ($opts{'i'}) to read text: $!"; } else { print "Enter some text: "; $text_from_console = ; } # now randomly insert the specified HTML tag into the text: my $tagged_text = ''; my $unclosed_tag = 0; while (my $line = $opts{'i'} ? : $text_from_console) { my $char; while (length($char = substr($line, 0, 1, ''))) { if ($char !~ /\s/ # skip spaces. and int rand 2) # 0 or 1. { # add the opening tag unless the previous character is # within a tag that has yet to be closed: $tagged_text .= $opening_tag unless ($unclosed_tag); $tagged_text .= $char; $unclosed_tag = 1; } else { # Either this is a space or a non-space character that # was rejected by rand(). Regardless, close the last tag # if it's still open: if ($unclosed_tag) { $tagged_text .= $closing_tag; $unclosed_tag = 0; } $tagged_text .= $char; } } # break if we got text from the console instead of from a file, since # there's nothing left: last unless ($opts{'i'}); } close INFILE if ($opts{'i'}); if (my $output_file = $opts{'o'} || $opts{'i'}) { # print the text with tags inserted into it to a file: open(OUTFILE, "> $output_file") || die "Couldn't file ($output_file) to save text: $!"; print OUTFILE $tagged_text; close OUTFILE; print "Saved text to $output_file.\n"; } else { print "\n$tagged_text"; } sub usage { print <<'END_OF_USAGE'; This script randomly inserts a specified HTML tag into some text. Usage: $ taginserter [FLAGS | OPTIONS...] Options: -t The name of the tag you want inserted (e.g., "b" for (bold), "i" for (italic), etc.). -i (Optional.) The file which taginserter will read the text you want tags inserted into from. If this isn't supplied, then you'll be prompted to enter some text. -o (Optional.) The file where you want the text outputted to after the tags have been inserted. If you don't supply this, then the filename you supplied to the -i option will be used instead. If you didn't supply a filename to -i, then the text will be printed out to the console. Flags: -h Displays this message. END_OF_USAGE exit; }