Code Examples for Class 10

example-01.pl

#! /usr/bin/env perl
use strict;
use warnings;
use File::Basename;

die "usage: example-01 filepath\n" unless scalar(@ARGV);
  
my $full = shift( @ARGV );

my ($filename, $dir, $suffix);
($filename, $dir, $suffix) =
    File::Basename::fileparse( $full );
print "-> '$filename' '$dir', '$suffix'\n";

($filename, $dir, $suffix) =
    fileparse( $full, qr/.(py|pl)/ );
print "-> '$filename' '$dir', '$suffix'\n";

example-03.pl

#! /usr/bin/env perl
use strict;
use warnings;
use Time::ParseDate;

my $TimeStr = scalar(@ARGV) ? shift(@ARGV) : `/bin/date`;
chomp $TimeStr;
my $Seconds = parsedate( $TimeStr );
print "$TimeStr = $Seconds\n";
print "= " . localtime( $Seconds ) . "\n";

example-03.pl

#! /usr/bin/env perl
use strict;
use warnings;
use Time::ParseDate;

my $TimeStr = scalar(@ARGV) ? shift(@ARGV) : `/bin/date`;
chomp $TimeStr;
my $Seconds = parsedate( $TimeStr );
print "$TimeStr = $Seconds\n";
print "= " . localtime( $Seconds ) . "\n";

example-04.pl

#! /usr/bin/env perl
use strict;
use warnings;

open( IFCONFIG, "/sbin/ifconfig|" )
    or die "Can't run ifconfig";
my $Adaptor = "";
while( <IFCONFIG> ) {
  if( /^(\w+)\s+Link/ ) {
    $Adaptor = $1;
  }
  elsif ( /inet addr:((\d+\.){3}\d+)/ ) {
    print "$Adaptor: $1\n";
  }
}

example-05.pl

#! /usr/bin/env perl
use strict;
use warnings;

sub GetInterfaces()
{
  open(IFCONFIG, "/sbin/ifconfig|") or die "Can't run ifconfig";
  my $Adapter = "";
  my %Adapters;
  while( <IFCONFIG> ) {
    if( /^(\w+)\s+Link/ ) {
      $Adapter = $1;
    }
    elsif( $Adapter ne ""  and  /inet addr:((\d+\.){3}\d+)/ ) {
      $Adapters{$Adapter} = $1;
    }
  }
  return \%Adapters;
}

die "usage: example-05 ifname" unless scalar(@ARGV) == 1;
my $Name = $ARGV[0];
my $All = GetInterfaces();
if( exists $All->{$Name} ) {
  print "$Name => $All->{$Name}\n";
}
else {
  print "$Name not found\n";
}

example-06.pl

#! /usr/bin/env perl
use strict;
use warnings;
use example_06;

die "usage: example-06 ifname" unless scalar(@ARGV) == 1;
my $Name = $ARGV[0];
InitializeInterfaces();
my $All = GetInterfaces();
if( exists $All->{$Name} ) {
  print "$Name => $All->{$Name}\n";
}
else {
  print "$Name not found\n";
}

example_06.pm

#! /usr/bin/env perl
use strict;
use warnings;

my %Adapters;
sub InitializeInterfaces()
{
  open(IFCONFIG, "/sbin/ifconfig|") or die "Can't run ifconfig";
  my $Adapter = "";
  while( <IFCONFIG> ) {
    if( /^(\w+)\s+Link/ ) {
      $Adapter = $1;
    }
    elsif( $Adapter ne ""  and  /inet addr:((\d+\.){3}\d+)/ ) {
      $Adapters{$Adapter} = $1;
    }
  }
}
sub GetInterfaces()
{
  return \%Adapters;
}
1;