Showing entries with tag "ARGV".

Found 3 entries

Perl: Read from multiple files with one filehandle

I have a directory of data files I wanted to read line-by-line simply. You can loop through each file, open a filehandle, process the lines, close the filehandle, but that can be repetitive. Perl has a unique mechanism where it will iterate across all the files in the @ARGV array automatically. You can fake out the @ARGV array with your own list of files and then iterate accordingly:

local @ARGV = sort(glob("/tmp/data/*.txt"));

# Special ARGV filehandle reads all the files sequentially
while (my $line = readline(ARGV)) {
    print $line;
Leave A Reply

Perl: Quick extract variables from @ARGV

I'm a big fan of Getopt::Long, but sometimes I do not want to include a large module to extract two arguments. I wrote a quick function that will parse simple command line arguments and give you a hash of their values.

sub argv {
    state $ret = {};

    if (!%$ret) {
        for (my $i = 0; $i < scalar(@ARGV); $i++) {
            # If the item starts with "-" it's a key
            if ((my ($key) = $ARGV[$i] =~ /^--?([a-zA-Z_]\w*)/) && ($ARGV[$i] !~ /^-\w\w/)) {
                # If the next item does not start with "--" it's the value for this item
                if (defined($ARGV[$i + 1]) && ($ARGV[$i + 1] !~ /^--?\D/)) {
                    $ret->{$key} = $ARGV[$i + 1];
                    $ARGV[$i]    = $ARGV[$i++] = undef; # Flag key/val to be removed
                } else { # Bareword like --verbose with no options
                    $ARGV[$i] = undef; # Flag item to be removed
        @ARGV = grep { defined($_); } @ARGV; # Remove processed items from ARGV

    if (defined($_[0])) { return $ret->{$_[0]}; } # Return requested item

    return $ret;

Note: I also wrote a similar implementation for PHP

Leave A Reply

Iterate over arguments in bash

Here is how you iterate over the list of command line arguments (ARGV) in bash

for var in "$@"
    echo "$var"
Leave A Reply