1 / 39

IO Basics

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.

sol
Download Presentation

IO Basics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. IO Basics

  2. Input from Standard Input while (defined($line = <STDIN>)) { print “I saw $line”; } - A Shortcut: while (<STDIN>) { print; }

  3. STDIN in List Context @lines = <STDIN> OR foreach (<STDIN>) { print “I saw $_”; }

  4. 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

  5. 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

  6. 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!

  7. 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.

  8. 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

  9. 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;

  10. printf format strings

  11. 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%

  12. File Handles • Names a connection between perl process and system. • Named like other perl identifiers • No prefix chars - use uppercase.

  13. Perl’s Special Filehandles • STDIN • STDOUT • STDERR • DATA • ARGV • ARGVOUT

  14. 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?

  15. 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

  16. Opening a File Handle open CONFIG, "dino"; open (CONFIG, "<dino”); open BEDROCK, ">fred"; open LOG, ">> $logfile"; • Perl 5.6 and above: open CONFIG, “<“, “dino”;

  17. 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"; }

  18. 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

  19. 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: $!"; }

  20. 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

  21. Reading from File Handles if (! open PASSWD, "/etc/passwd”) { die “Can’t open ($!)”; } while (<PASSWD>) { chomp; if (/^root:/) {...} }

  22. Writing • You can write to a filehandle using print or printf: print MYFILE ”The output: $output”; printf STDERR "Error number %d\n", $errno;

  23. 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.

  24. Buffered Output • Use $| (dollar pipe) to control buffering select LOG; $| = 1; select STDOUT; #later in program... print LOG “Unbuffered output”;

  25. 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.

  26. Hashes

  27. 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.

  28. Why use a Hash? • To pair data, eg • Given name, family nmae • Hostname, ip address

  29. Hash Element Access $hash {$some_key}; $surname {“Fred”} = “Flinstone”; $surname{“Barney”} = “Rubble”; foreach $person (qw <Barney Fred>){ print “$person $surname{$person}\n”; }

  30. 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

  31. 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

  32. The Whole Hash %newhash = %oldhash; • Reverse keys and values: %hostname = reverse %ip_addr

  33. The Big Arrow • Assigning a hash by a list is confusing, instead we can use => my %surname = { “Fred” => “Flinstone”, “Barney” => “Rubble”, };

  34. Hash Functions my %hash = (“a”=>1, “b”=>2, “c”=>3); my @k = keys %hash; my @v = values %hash; my $count = keys %hash

  35. 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….

  36. Processing hash with foreach foreach $key (sort keys %hash) { print “$key => $hash{$key}; }

  37. The Exists Function • Determines if a key exists in a hash: if (exists $books{“dino”} ) { print “Dino has a library card”; }

  38. The Delete Function • Removes a key from a hash delete $books {“betty”}; • exists $books{“betty”} would now return false.

  39. Hash Element Interpolation • Works as you would expect for single elements: print “$books{$person}”; • Cannot print the whole hash like you would an array.

More Related