Parse Command Line arguments

Bash

#!/bin/bash
OPTIND=1           # reset in case getopts has been used previously
# default settings
output=""
verbose=0
while getopts "h?vf:" opt; do
    case "$opt" in
    h|\?)  show_help; exit 1;;
    v) verbose=1;;
    f) output=$OPTARG;;
    esac
done

shift $((OPTIND-1))
[ "$1" = "--" ] && shift;
echo "verbose=$verbose, output=$output, leftover: $@"

Reference:

Perl

#! /usr/bin/env perl

use strict;
use warnings;
use Getopt::Std;

sub usage {
    print "usage:\n".
          "$0 -hvf other_list\n".
          "  -h     help\n".
          "  -v     verbose\".
          "  -f file output file\n".
          "\n";
    exit 1;
}

my %opts;
my $rc = getopts('hvf:', \%opts);
usage() if ($rc || $opts{h});
print "options:\n";
print "$_: $opts{$_}\n" foreach (sort keys %opts);
print "leftovers: @ARGV\n";

Reference:

Python

#! /usr/bin/env python

import argparse

parser = argparse.ArgumentParser()
parser.ad_argument('-f', '--output_file', type=str,
                     default='my_output', help='output file name')
parser.add_argument('-v', '--verbose', action='store_true', help='verbose mode')
args = parser.parse_args()
if args.verbose:
    print 'verbose mode'
with open(args.output_file, 'w') as f:
    # do something
    pass

Reference:

C/C++

under construction

Advertisements

Perl Tricks – each %hash

Perl has three ways to iterate a hash:

  • keys %hash iterates keys
  • values %hash iterates values
  • each %hash iterates the pair (key, value)

Perl contains an internal iterator for such kind of iteration. So far so good, as long as you finish the iteration every time. What if you break the iteration before it finishes, and start a new iteration later? According to perl doc, the iterator is reset only when

  • end of iteration
  • keys or values is called

so the script might not work as you expect in the following pattern:

while (my ($k, $v) = each %hash) {
      # do some work
      last if ($k == $somekey || $v == $somevalue);
}
# sometime later
while (my ($k, $v) = each %hash) {  # iterator is not reset if the previous while not finish
         # some work
}

The conclusion – don’t use each if you plan to break the iteration, use keys instead.