#!/usr/bin/perl -w use strict; use warnings; ######################################## my $INPUT_FILE_NAME; my $OUTPUT_FILE_NAME; Init(); my @LINES = ReadTextFile($INPUT_FILE_NAME); # DO SOMETHING CreateFile($OUTPUT_FILE_NAME, join("\n", @LINES)) or die("Can't write to file...\n\n"); print "SUCCESS!\n\n"; exit; ######################################## sub Init { my $SELF = GetFileName($0); $INPUT_FILE_NAME = (@ARGV) ? $ARGV[0] : ''; $INPUT_FILE_NAME or die("\nUsage: $SELF \n\n"); $OUTPUT_FILE_NAME = $INPUT_FILE_NAME . '.out'; } # Usage: STRING = Trim(STRING) - Removes whitespace, newline characters and other special characters before and after STRING. Returns a new string. sub Trim { @_ or return ''; my $T = $_[0]; defined $T or return ''; my $N = length($T); my $X = 0; my $Y = 0; while ($N--) { if (vec($T, $N, 8) > 32) { $X = $N; $Y or $Y = $N + 1; } } return substr($T, $X, $Y - $X); } # Usage: FILE_NAME_ONLY = GetFileName(FULL_NAME) - Returns only the name portion of a full file name. sub GetFileName { @_ or return ''; my $W = shift; defined $W or return ''; length($W) or return ''; $W =~ tr|\\|/|; return substr($W, rindex($W, '/') + 1, length($W)); } # Usage: STRING = _FileName(\@_) - Removes the first argument from @_ just like shift() does and returns a file name. This function does not check syntax, but it does remove some illegal characters (<>|*?) from the name that obviously should not occur in a file name. If the file name doesn't contain any valid characters, then returns an empty string. sub _FileName { @_ or return ''; my $N = shift; $N = shift(@$N); defined $N or return ''; length($N) or return ''; my $c; my $j = 0; my $V = 0; for (my $i = 0; $i < length($N); $i++) { $c = vec($N, $i, 8); next if ($c == 63 || $c == 42 || $c < 32); last if ($c == 60 || $c == 62 || $c == 124); if ($c > 32) { $V = $j + 1; } if ($V) { $i == $j or vec($N, $j, 8) = $c; $j++; } } return substr($N, 0, $V); } # Usage: ARRAY = ReadTextFile(FILE_NAME, [LIMIT]) - Reads the contents of a text file and returns the lines in an array. If a second argument is provided, then only the first few lines will be processed. Each line is trimmed before it is stored. sub ReadTextFile { my @A; my $F = _FileName(\@_); length($F) or return @A; my $M = @_ ? shift : 99999999; defined $M or return @A; $M or return @A; -f $F or return @A; -s $F or return @A; my $H; my $B; my $i = 0; open $H, "<$F" or return @A; while (my $L = <$H>) { $A[$i++] = Trim($L); $i < $M or last; } close $H; return @A; } # Usage: STATUS = CreateFile(FILE_NAME, STRING) - Creates and overwrites a file. Returns 1 on success or 0 if something went wrong. sub CreateFile { my $F = _FileName(\@_); length($F) or return 0; my $S = (@_) ? shift : ''; return 0 unless defined $S; open(my $H, ">$F") or return 0; if (length($S)) { print $H $S or return 0; } close $H or return 0; return 1; }