Skip to content

Instantly share code, notes, and snippets.

@kazu634
Created December 25, 2011 14:04
Show Gist options
  • Save kazu634/1519306 to your computer and use it in GitHub Desktop.
Save kazu634/1519306 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
# for formality's sake
use strict;
use warnings;
# Handling the options
use Getopt::Long;
# Default value
my $header = "src/header"; # default value for header file
my $procedure = "src/procedure";
my $footer = "src/footer"; # default value for footer file
my $help;
my $result = GetOptions(
"header=s" => \$header,
"procedure|proc=s" => \$procedure,
"footer=s" => \$footer,
"help|h" => \$help,
);
# show usage if needed and exit 0:
if ($help) {
&usage;
exit 0;
}
# check whether the files (header, procedure, footer) exist
if ( not( -e $header ) ) {
warn "$header does not exist.\n";
&usage;
exit 1;
}
elsif ( not( -e $procedure ) ) {
warn "$procedure does not exist.\n";
&usage;
exit 1;
}
elsif ( not( -e $footer ) ) {
warn "$footer does not exist.\n";
&usage;
exit 1;
}
&readFileDoSomething( $header, sub { my $str = shift; return $str } );
&readFileDoSomething( $procedure,
sub { my $str = shift; return "[memo] " . $str; } );
&readFileDoSomething($footer, sub {my $str=shift; return $str;});
# ------------------
# --- subroutine ---
# ------------------
# readFileDoSomething:
# - explanation: Read from a file line by line,
# modify it according to the callback function,
# and print these lines.
# - arguments: filename and callback in this order
# - filename: a string to specify the filename to be read
# - callback: a reference to a subroutine.
# The subroutine is called with each line of the filename given.
# The subroutine must be return string.
sub readFileDoSomething {
# arguments
my ( $file, $callback ) = @_;
# read file
open( my $fh, "<", $file )
or die "Cannot open $file: $!";
# printing the contents of the file
while ( my $line = readline $fh ) {
print &$callback($line);
}
}
sub usage {
print "Usage: blahblahblah\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment