Code Examples for Class 04

example-01.pl

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

my $file = "example-01.txt";
if(!open(IN, $file) ) {
  die "Can't read input file '$file'";
}
while(my $line = <IN>) {
  if(index($line, "Important") >= 0) {
    print $line;
  }
}
close(IN);

example-01.py

#! /usr/bin/env python

f = open( "example-01.txt" )
for line in f.readlines() :
    if line.count( "Important" ) > 0 :
        print line.strip()
f.close()

example-01.rb

#! /usr/bin/env ruby

IO.foreach('example-01.txt') do |line|
    if line.index('Important') != nil
        puts line
    end
end 

example-01-short.pl

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

my $file = "example-01.txt";
open( IN, $file ) or
  die "Can't read input file '$file'";
while( <IN> ) {
  print if(/Important/);
}
close(IN);

example-01.txt

random stuff
more random stuff
Important stuff
other stuff

example-02.pl

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

if (scalar(@ARGV) != 2) {
  die "usage: example-01 string int";
}
my $s = $ARGV[0];
my $i = int($ARGV[1]);

print "s is '", $s, "', i is ", $i, "\n";

example-02.py

#! /usr/bin/env python
import sys

if len(sys.argv) != 3 :
    print >>sys.stderr, "usage: example-02 string int\n"
    sys.exit( 1 )
s = sys.argv[1]
i = int(sys.argv[2])
print "s = '"+s+"', i =", i

example-02.rb

#! /usr/bin/env ruby

if ARGV.size != 2
    warn "usage: example-02 string int"
    exit 1
end
s = ARGV[0]
i = Integer(ARGV[1])
puts 's = "'+s+'", i = '+i.to_s() 

example-03.pl

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

die "usage: example-03 directory" unless scalar(@ARGV) == 1;
my $dir = shift(@ARGV);
die "$dir isn't a directory" unless -d $dir;
foreach my $path(<$dir/*>) {
  if (-d $path) {
    print "$path is a directory\n";
  } elsif (-f $path) {
    print "$path is a file\n";
  } else {
    print "I don't know what $path is\n";
  }
}

example-03.py

#! /usr/bin/env python
import sys
import os
import glob

if len(sys.argv) != 2 :
  print >>sys.stderr, "usage: example-03 directory"
  sys.exit(1)
dirpath = sys.argv[1]
if not os.path.isdir( dirpath ) :
  print >>sys.stderr, dirpath, "isn't a valid directory"
  sys.exit(1)
for path in glob.glob( dirpath+"/*" ) :
  if os.path.isdir( path ) :
    print path, "is a directory"
  elif os.path.isfile( path ) :
    print path, "is a file"
  else :
    print "I don't know what", path, "is"

example-03.rb

#!/usr/bin/env ruby
unless ARGV.size == 1
  warn "usage: example-02 string"
  exit 1
end
dirpath = ARGV[0]
unless File.directory?(dirpath)
  warn "#{dirpath} isn't a valid directory"
  exit 1
end
Dir.glob("#{dirpath}/*").each do |path|
  if File.directory?(path)
    puts "#{path} is a directory"
  elsif File.file?(path)
    puts "#{path} is a file"
  else
    puts "I don't know what #{path} is"
  end
end