When encoding:
#! perl
use strict;
use warnings;
use 5.010;
use Getopt::Long;
use Pod::Usage;
use autodie;
my %opts = (
infile => '-',
outfile => '-',
);
GetOptions (
'encode|e' => \$opts{encode},
'decode|d' => \$opts{decode},
'infile|i=s' => \$opts{infile},
'outfile|o=s' => \$opts{outfile},
'help|h' => \&help,
'man|m' => \&man,
);
unless(
# exactly one of these should be set
$opts{encode} xor $opts{decode}
){
help();
}
{
my $infile;
if( $opts{infile} ~~ ['-', '&0'] ){
$infile = *STDIN{IO};
}else{
open $infile, '<', $opts{infile};
}
my $outfile;
if( $opts{outfile} ~~ ['-', '&1'] ){
$outfile = *STDOUT{IO};
}elsif( $opts{outfile} ~~ '&2' ){
$outfile = *STDERR{IO};
}else{
open $outfile, '>', $opts{outfile};
}
if( $opts{decode} ){
while( my $line = <$infile> ){
chomp $line;
say {$outfile} $line;
}
}elsif( $opts{encode} ){
while( my $line = <$infile> ){
chomp $line;
$line =~ s/[\W_]+/ /g;
say {$outfile} $line;
}
}else{
die 'How did I get here?';
}
}
sub help{
pod2usage();
}
sub man{
pod2usage(1);
}
__END__
=head1 NAME
sample.pl - Using GetOpt::Long and Pod::Usage
=head1 SYNOPSIS
sample.pl [options] [file ...]
Options:
--help -h brief help message
--man -m full documentation
--encode -e encode text
--decode -d decode text
--infile -i input filename
--outfile -o output filename
=head1 OPTIONS
=over 8
=item B<--help>
Print a brief help message and exits.
=item B<--man>
Prints the manual page and exits.
=item B<--encode>
Removes any character other than /\w/.
=item B<--decode>
Just reads from one file, and writes to the other.
=item B<--infile>
Input filename. If this is '-' or '&0', then read from STDIN instead.
If you use '&0', you must pass it in with quotes.
=item B<--outfile>
Output filename. If this is '-' or '&1', then write to STDOUT instead.
If this is '&2', then write to STDERR instead.
If you use '&1' or '&2', you must pass it in with quotes.
=back
=head1 DESCRIPTION
B will read the given input file(s) and do something
useful with the contents thereof.
=cut
echo Hello, this is, some text | perl sample.pl -e Hello this is some text