eTechtips

Tech Tips and Insights

Category: Programming

  • Perl: Open and read file line by line

    I regularly have to process Comma Seperated Value or CSV files, usually for user lists. So the following perl code is a framework for processing a file line by line.

    #!/usr/bin/perl
    use strict;
    my $line;
    
    open(FILEIN, "filename.txt");
    
    while(<FILEIN>)
    {
      chomp();
      $line = $_;
      # Process $line for data
      # Example seperating line by commas: 
      my ($username,$firstname,$lastname,$email) = split(/,/,$line);
    }
    
    close(FILEIN);
    
    0 Comments
  • Perl: Hashes

    Here are some basics about Perl hashes that can be helpful to be used when an you need to associate a label with some value such as for names and telephone numbers or account numbers with amounts owed.

    Create a hash variable.

    my %hashvar;
    

    Create a hash reference

    my $refhash = {};
    

    Add a value to a hash variable.

    $hashvar{'somekey'} = 'someval';
    

    Add a value to a hash reference.

    $hashref->{'somekey'} = 'someotherval';
    

    Access a value in a hash.

    print $hashvar{'somekey'};
    

    Access a value in a hash reference.

    print $hashref->{'somekey}';
    

    Access all Keys in a hash variable.
    foreach my $k (keys(%hashvar))
    {
    print $hashvar{$k};
    }

    Access all Keys in a hash reference.

    foreach my $k (keys(%$hashref))
    {
      print $k . "n";
    }
    

    Access all Keys and values in a hash.

    while (my ($key,$value) = each %hashvar)
    {
      print "Key: " . $key . " has value:" . $value . "n";
    }
    

    Access all Keys and values in a hash.

    while (my ($key,$value) = each %$refhash)
    {
      print "Key: " . $key . " has value:" . $value . "n";
    }
    

    Assigning multiple values to a hash

    %hasvar = (
      'test2' => 'myval',
      'test3' => 'myval3'
    );
    

    Note: This will clear the existing hash.

    Delete a value from a hash

    delete $hashvar{'key1'};
    

    Delete a value from a hash reference.

    delete $hashref->{'key1'};
    
    0 Comments
  • Perl: Arrays

    I use perl arrays in some of my programs, and just started to look at the regular things that I do with these arrays and thought it would be useful to keep a list of frequently used items.

    Create a variable specified as an array.

    my @vararray
    

    Add an item to the beginning of an array

    unshift (@vararray, "File2");
    

    Add an item to the end of an array

    push (@vararray, "File1");
    

    Remove an item from the beginning of an array

    my $var = shift(@array);
    

    Remove an item from the end of an array

    pop(@array)
    

    Clear an array

    @vararray = ();
    

    Address an item in an array

    print $vararray[0] ; 
    

    Get the size of an array

    my $arraysize = @array;
    

    Remove an item based on the index

    delete @vararray[1];
    

    Iterate over an array

    foreach my $var (@vararay)
    {
      print "$var n";
    }
     
    # or 
    my $size = @vararray;
    my $i;
    for ($i = 0 ; $i < @size; $i++)
    {
      print "$vararray[$i]n";
    }
    
    0 Comments
  • Linux System utilization tools

    I was asked about system utilization on Linux systems. I found thesystatset of tools which consist of: sar, sadf, mpstat, iostat, nfsiostat, cifsiostat, pidstat and sa tools.

    I will talk about the iostat tool in this article and follow up about some of the other tools.

    On Ubuntu or debian systems you can install this toolset with:

    sudo apt-get install sysstat

    Then you will have access to the iostat command. The command output from executing with no options is below:

    # iostat
    Linux 2.6.32-33-generic (sumo)  09/01/2011      _i686_  (2 CPU)
    
    avg-cpu:  %user   %nice %system %iowait  %steal   %idle
               0.11    0.00    0.47    0.01    0.00   99.41
    
    Device:            tps   Blk_read/s   Blk_wrtn/s   Blk_read   Blk_wrtn
    sda               0.54         1.85         8.91    1611385    7740024

    This displays the avg-cpu utilization and a device usage list with basic utilization.
    Some options you can use are

    Option Explanation
    -c Display CPU utilization only
    -d Display Device utilization only
    -k Display information in kilobytes
    -m Display information in megabytes
    -t Display time for each report
    -x Display extended statistics

    One more way to use the iostat tool is to specify an interval and count to the command

    iostat -d -x 10 5
    

    This will display the output 5 more times with 10 seconds between each run.

    1 Comment
  • How to exit python script

    When I was trying to terminate a python script after a failure, I tried to find the nicest way to exit. The sys.exit() command provided by importing the sys library was what I found.

    The function can take an optional numeric argument, usually in the range of 0-127, and with no argument it returns 0. The return code is passed back to the Operating System.

    import sys
    sys.exit(1)
    

    When exit returns a non-zero value, it is considered an error.

    0 Comments
  • Bash: test if file exists

    When you need to do some processing in bash and display if a file exists, the following is a simple script that takes the filename in the $testfile variable and reports if it exists or not.

    if [ -f $testfile ]
    then
      echo $testfile exists!
    else
      echo $testfile does not exist
    fi
    
    0 Comments
  • Linux:Script to find files

    I regularly have to find where a file is located and usually use find:

    find . | grep 
    

    Where is replaced with the filename or partial name to match. So I finally decided to write a script to just run this and allow me to print the matching names and even potentially pass the -i flag to grep.

    #!/bin/sh
    
    
    if [ $# -lt 1 ]; then
      echo 1>&2 Usage: $0 ""
      exit 127
    fi
    icase=
    
    while [ $# -ge 1 ]; do
       case $1 in
         -i)  icase=$1;;
          *)  search=$1 ;;
       esac
       shift
    done
    
    find .  | grep $icase $search
    

    This is just a simple script which I have named ffind that searches starting from the current directory. This lets me search with the following commands:

    ffind bak$
    

    This will search for all files that end with “bak” .

    ffind -i edr
    

    This will search for all files with “edr” regardless of case

    0 Comments
  • Using find and grep to search files

    I have been searching through source code and files for years. And I used to use find with a few arguments to get what I was looking for.

    find . -exec grep  {} ; -print

    I used the -print after the exec arguments to show the file only when the grep succeeded.  This worked but was a bit to type each time I used it. So I came up with a little script that would help me to search for the an argument and even allow a case insensitive search as well.
     

    #!/bin/sh
    
    if [ $# -lt 1 ]; then
      echo 1>&2 Usage: $0 ""
      exit 127
    fi
    icase=
    search=
    
    while [ $# -ge 1 ]; do
      case $1 in 
         -i) icase=$1;;
          *) search=$1 ;;
      esac
      shift
    done
    
    find . -type f -print0 | xargs -0 grep $icase $search

    The script takes at least one argument and excepts a ‘-i’ argument to make grep use a case insensitive search. This will print the file name and the line that matches the search term. It can be easily adapted to show the count of matched patterns (‘-c’) or the line number (‘-n’).

    0 Comments
  • How to add library paths to perl

    I need to write custom Perl libraries sometimes and an easy method to make sure that they are found on the path is to use the PERL5LIB environment variable.

    So either set it in your current environment or in a shell you can just specify the contents before you run your script.

    PERL5LIB=/PATH/WHERE/LIB/IS perl scripttorun.pl 
    0 Comments
  • Perl: CPAN installing modules

    Sometimes it is necessary to install other modules into the Perl environment. Luckily there is a great repository of modules known as CPAN (The Comprehensive Perl Archive Network). This lets you install modules to help with encryption, XML,YAML, and many other things. There are a few ways to install a package and here are the ones that I use the most.

    Using the CPAN shell:

    perl -MCPAN -e shell

    This will open a command prompt that will let you search for CPAN modules with:

    i /PACKAGENAME/

    or install a new module:

    install /DateTime/

    The nice thing about installing with CPAN is that it will look for the dependencies and suggest installing them before the module you requested.

    NOTE:This can take some time and your dependencies could have dependencies.

    The other method I use is to skip the CPAN prompt and just directly execute the install of the module:

    perl -MCPAN -e 'install DateTime'

    This is just the most basic of usage, and there is probably a lot more you can do, but I have not had to use much more than this.

    0 Comments