Code Examples for Class 13
example-01.pl
#! /usr/bin/env perl
use strict;
use warnings;
sub Print( $$ )
{
my( $key, $ref ) = @_;
print "$key: " . join( ", ", @{$ref} ) . "\n";
}
my %Data = ( foo => [ 1, 2, 3, 4 ],
bar => [ 0, 3, 5, 9 ],
blah => [ 1 ], );
foreach my $key ( keys %Data ) {
Print( $key, $Data{key} );
}
example-01b.pl
#! /usr/bin/env perl
use strict;
use warnings;
sub Print( $$ )
{
my( $key, $ref ) = @_;
print "<$key> <$ref>\n";
print "$key: " . join( ", ", @{$ref} ) . "\n";
}
my %Data = ( foo => [ 1, 2, 3, 4 ],
bar => [ 0, 3, 5, 9 ],
blah => [ 1 ], );
foreach my $key ( keys %Data ) {
Print( $key, $Data{key} );
}
example-01c.pl
#! /usr/bin/env perl
use strict;
use warnings;
sub Print( $$ )
{
my( $key, $ref ) = @_;
print "$key: " . join( ", ", @{$ref} ) . "\n";
}
my %Data = ( foo => [ 1, 2, 3, 4 ],
bar => [ 0, 3, 5, 9 ],
blah => [ 1 ], );
foreach my $key ( keys %Data ) {
Print( $key, $Data{$key} );
}
example-01.run
bash-3.2$ perl example-01.pl
Can't use an undefined value as an ARRAY reference at example-01.pl line 8.
bash-3.2$ perl -d example-01.pl
Loading DB routines from perl5db.pl version 1.28
Editor support available.
Enter h or `h h' for help, or `man perldebug' for more help.
main::(example-01.pl:12): my %Data = (
main::(example-01.pl:13): foo => [ 1, 2, 3, 4 ],
main::(example-01.pl:14): bar => [ 0, 3, 5, 9 ],
main::(example-01.pl:15): blah => [ 1 ],
main::(example-01.pl:16): );
DB<1>
example-02.pl
#! /usr/bin/env perl
use strict;
use warnings;
my $file = "/etc/does.not.exist";
open(IN, $file ) or
die "Unable to open file - $file";
while( <IN> ) {
print;
}
close( IN );
example-03.pl
#! /usr/bin/env perl
use strict; use warnings;
die "usage: example <file>" unless scalar(@ARGV) == 1;
my $file = shift(@ARGV);
eval {
open(FILE, $file ) or
die "Unable to open file '$file'";
};
if ($@) {
print "Ahh: $@";
}
else {
while( <FILE> ) {
print;
}
close( FILE );
}
print "bye\n";
example-03.py
#! /usr/bin/env python
import sys
if len(sys.argv) != 2 :
print >>sys.stderr, "usage: example <file>"
exit(1)
fname = sys.argv[1]
try:
fh = open( fname )
for line in fh.readlines() :
print line,
fh.close()
except Exception, e:
print "Failed to open", fname, ":", e
exit(1)
example-03.rb
#! /usr/bin/env ruby
unless ARGV.size == 1
warn "usage: example <file>"
exit 1
end
file = ARGV[0]
begin
IO.foreach(file) do |line|
puts line
end
rescue
$stderr.print "IO failed: " + $!
raise
end
example-04.pl
#! /usr/bin/env perl
use strict;
use warnings;
sub Load($$)
{
my( $name, $feature ) = @_;
eval "require $name";
if( $@ ) {
print STDERR "Can't find $name: $feature disabled;\n";
}
else {
import $name;
}
}
Load( "BadModule", "Something stupid" );
Load( "Time::ParseDate", "Date parsing" );