390 likes | 541 Views
IO Basics. Input from Standard Input. while (defined($line = <STDIN>)) { print “I saw $line”; } - A Shortcut: while (<STDIN>) { print; }. STDIN in List Context. @lines = <STDIN> OR foreach (<STDIN>) { print “I saw $_”; }. The Diamond Operator.
E N D
Input from Standard Input while (defined($line = <STDIN>)) { print “I saw $line”; } - A Shortcut: while (<STDIN>) { print; }
STDIN in List Context @lines = <STDIN> OR foreach (<STDIN>) { print “I saw $_”; }
The Diamond Operator • Used for making unix-like utilities • Useful when you are processing text • Perl reads input from the files named on the command line in sequence • If there are no args it reads from stdin
More on Diamond while (<>) { print $_; } • Multiple input files will transfer seamlessly (as if there was no EOL) • $ARGV contains name of current file • Hyphen means stdin
Invocation Arguments • Stored in an array called @ARGV • Can be treated like any other array • The diamond operator checks @ARGV for filenames. If you alter @ARGV, you alter which files diamond reads from!
STDOUT and Print • Print sends its output to STDOUT print @array; print “@array”; • STDOUT is buffered • Buffer is flushed when it is full or when program ends.
Print Continued… • Print in list context: print <>; print sort <>; • Use parenthesis to add function calls print (2+3); #prints 5 print (2+3)*4; #prints 5 print ((2+3)*4); #prints 20
printf • print has limitations when it comes to formatted output • printf uses a format string for output: printf “%s expires in %d days”, $user, $days;
printf continued… • You can print in columns: printf “%6d”, 42 #----42 printf “%10s”, hello #-----hello printf “%-10s”, hello #hello----- printf “%12f”, 20/3 #----6.666667 printf “%12.3f”, 20/3 #-------6.667 printf “%3.0f”, 20/3 #--7 printf “Rate: %.2f%%”, 5.25/12 # Rate: 0.44%
File Handles • Names a connection between perl process and system. • Named like other perl identifiers • No prefix chars - use uppercase.
Perl’s Special Filehandles • STDIN • STDOUT • STDERR • DATA • ARGV • ARGVOUT
Input Redirection and Pipes $ ./your_program <dino >wilma • Tells your_program to use file dino for input, and output to file wilma. • Pipelines • $ cat fred barney | ./your_program | lpr • - But what happens if "your_program" needs to report an error?
STDERR • An output stream, like STDOUT • Is redirected independent of STDOUT - if STDOUT goes to a file, STDERR usually goes to the terminal. • Not buffered. • To redirect STDERR to a file: $ netstat | ./your_program 2> /tmp/my_errors
Opening a File Handle open CONFIG, "dino"; open (CONFIG, "<dino”); open BEDROCK, ">fred"; open LOG, ">> $logfile"; • Perl 5.6 and above: open CONFIG, “<“, “dino”;
Bad Filehandles • Sometimes files can’t be opened, • Reading from a bad filehandle gives EOF • Data written to a bad file handle is discarded. • Check the return value of open: my $success = open LOG, ">>logfile"; if (! $success) { print "couldn't open file"; }
Closing a File Handle • When you are finished with it: close BEDROCK; • Tells perl to flush buffers and close stream • Frees file for use by others • Perl will close a file handle automatically if you reopen it or exit the program
Fatal Errors with Die • Use die to make your program quit with an error message • Die ensures your program has a nonzero exit status to indicate an error to OS. : if (! open LOG, ">>logfile") { die "Cannot create logfile: $!"; }
Warnings with Warn • Can use warn to make a warning that acts like a perl builtin warning. • Warn works just like die (writes to STDERR) but does not quit program
Reading from File Handles if (! open PASSWD, "/etc/passwd”) { die “Can’t open ($!)”; } while (<PASSWD>) { chomp; if (/^root:/) {...} }
Writing • You can write to a filehandle using print or printf: print MYFILE ”The output: $output”; printf STDERR "Error number %d\n", $errno;
Changing the Default Output • By default, print will go to STDOUT • Change this with select: select BEDROCK; print “My output for Bedrock”; • Will stay this way for the rest of the program or until you select STDOUT.
Buffered Output • Use $| (dollar pipe) to control buffering select LOG; $| = 1; select STDOUT; #later in program... print LOG “Unbuffered output”;
Reopening a Standard File Handle • Reopening a file handle closes the old file handle: open STDERR, “>>error.log” or die “can’t open” • If a standard file handle can’t be written to perl restores the original.
Hashes • Originally called associative arrays • Stores indexed data like an array • Indexes with strings instead of numbers • Keys must be unique, values can be duplicate.
Why use a Hash? • To pair data, eg • Given name, family nmae • Hostname, ip address
Hash Element Access $hash {$some_key}; $surname {“Fred”} = “Flinstone”; $surname{“Barney”} = “Rubble”; foreach $person (qw <Barney Fred>){ print “$person $surname{$person}\n”; }
Hash Access Continued • Hash names are like other perl identifiers. • Separate namespace • Accessing outside the hash gives undef. • Storing something in an existing hash element overwrites previous value
The Whole Hash • To refer to the hash as a whole, use % %surname • Can assign using a list %surname = (“Fred”, “Flinstone”, “Barney”, “Rubble”); • Unwind the hash: @myarray = %myhash
The Whole Hash %newhash = %oldhash; • Reverse keys and values: %hostname = reverse %ip_addr
The Big Arrow • Assigning a hash by a list is confusing, instead we can use => my %surname = { “Fred” => “Flinstone”, “Barney” => “Rubble”, };
Hash Functions my %hash = (“a”=>1, “b”=>2, “c”=>3); my @k = keys %hash; my @v = values %hash; my $count = keys %hash
The Each Function • Allows you to process every element in a hash while ( ($key, $value) = each %hash ) { print “$key => $value\n”; } OR we can use foreach….
Processing hash with foreach foreach $key (sort keys %hash) { print “$key => $hash{$key}; }
The Exists Function • Determines if a key exists in a hash: if (exists $books{“dino”} ) { print “Dino has a library card”; }
The Delete Function • Removes a key from a hash delete $books {“betty”}; • exists $books{“betty”} would now return false.
Hash Element Interpolation • Works as you would expect for single elements: print “$books{$person}”; • Cannot print the whole hash like you would an array.