1 / 20

Programming Language Concepts Perl I/O

Explore Perl I/O functionalities and advanced concepts to enhance your programming skills. Learn about file operations, formatted output using printf, arrays, and more. Get hands-on experience with practical examples and exercises.

eckerte
Download Presentation

Programming Language Concepts Perl I/O

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. Programming Language ConceptsPerl I/O Adapted by Carl Reynolds from materials by Sean P. Strout PLC - Perl I/O (v2.1)

  2. Input from Standard Input • The line input operator will return undef on EOF while (defined($line = <STDIN>)) { print “I saw $line”; } • Perl provides a scalar context shortcut to read one line of input at a time and evaluate the loop while (<STDIN>) { while(defined($_=<STDIN>)) { print “I saw $_”; print “I saw $_”; } }  PLC - Perl I/O (v2.1)

  3. Input from Standard Input • In a list context, all lines of input must be read into memory before the looping operation can begin foreach (<STDIN>) { print “I saw $_”; } • For extremely large input files, the scalar context (while) is usually the more efficient programming approach. PLC - Perl I/O (v2.1)

  4. The Diamond Operator • Use the diamond operator, <> , to make your programs work like standard Unix utilities: cat, grep, lpr, etc. % ./myprog.pl fred barney - betty while (defined($line = <>)) { chomp($line); print “It was $line that I saw!\n”; } • The diamond operator reads input, and stores it into $_ by default • The command line input files look like a single, continuous input stream file file stdin file PLC - Perl I/O (v2.1)

  5. Invocation Arguments • The diamond operator finds its list of files by looking at the special array, @ARGV , which is a list of invocation arguments • The program name is stored in $0, not@ARGV • Read the input into $_ , 1 line at a time: while (<>) { chomp; print “I saw $_.”; } • (Use the Getopt::Std module to process Unix-style flags) • See Programming in Perl, Chapt. 7 ./myprog –f filename –o –r2 PLC - Perl I/O (v2.1)

  6. Output to Standard Output • Use the print operator to take a list of values and send each item to standard output @array = qw/ fred barney betty /; print @array; # fredbarneybetty print “@array”; # fred barney betty • What happens if: @array = <STDIN>; print “@array”; • Your turn. Write a Perl script for the basic Unix cat and sort commands… print <>; print sort <>; PLC - Perl I/O (v2.1)

  7. Output to Standard Output • “If it looks like a function call, it is a function call” print “Hello world!\n”; # ok print (“Hello world!\n”); # ok $result = print (2+3); # prints “5”, $result=1 $result = print (2+3)*4; # What happens here? • With no parentheses, print is a list operator • Otherwise it is a function call which only operates on the stuff inside the parentheses. PLC - Perl I/O (v2.1)

  8. Formatted Output with printf • The printf operator takes a format string followed by a list of things to print $user = “Sarah Connor”; $days = 7; printf “Hello, %s; you expire in %d days”, $user, $days; #Hello, Sarah Connor; you expire in 7 days • Each conversion begins with a percent sign and ends with a letter • Use %g for expected number printing printf “%g %g %g\n”, 5/2, 51/17, 51**17; #2.5 3 1.0683e+29 PLC - Perl I/O (v2.1)

  9. Formatted Output with printf • Use %d for decimal integer printing (truncates) printf “in %d days”, 17.85 # in 17 days • To print formatted columnar data, specify a field width printf “%6d\n”, 42 # 4 spaces + 42 printf “%2d\n”, 2e3 + 1.95 # 2001 • To interpolate a value into a string, use %s printf “%10s\n”, “wilma”; # 5 spaces + wilma printf “%-15s\n”, “dino”; # dino + 11 spaces (left-justified) PLC - Perl I/O (v2.1)

  10. Formatted Output with printf • Use %f to control precision in floating-point rounds • Note: The . character counts as one character printf “%12f\n”, 6*7 + 2/3; # 3 spaces + 42.666667 printf “%12.3f\n”, 6*7 + 2/3; # 6 spaces + 42.667 printf “%12.0f\n”, 6*7 + 2/3; # 10 spaces + 43 • Use %perldoc perlfuncor look at your favorite C book for a complete list of conversions PLC - Perl I/O (v2.1)

  11. Arrays and printf • Printing arrays of variable items via printfcan be achieved with a bit of craftiness • Generate the format string “on the fly” my @items = qw/ wilma dino pebbles /; my $format = “The items are: \n” . (“%10s\n” x @items); print “the format is <<$format>>\n”; # for debugging printf $format, @items; • But can the apprentice become the master? Try to shorten the 3 lines in blue to 1... printf “The items are: \n” . (“%10s\n” x @items), @items; PLC - Perl I/O (v2.1)

  12. Test Your Understanding • Write a program that acts like cat, but reverses the order of the output lines (so call it ‘tac’). If you run yours as: ./my_tacfred barney betty The output should be all of file betty from last line to first, then barney and then fred, also from last line to first. print reverse <>; PLC - Perl I/O (v2.1)

  13. Filehandles • Use the openoperator to connect your program to a file stream open CONFIG, “dino”; # implicit read open CONFIG, “<dino”; # explicit read open BEDROCK,“>fred”; # create open LOG, “>>logfile”; # append (or create) • Use the close operator when finished with a file handle close BEDROCK; # forces flush • Re-opening a file handle causes an automatic close Filehandle PLC - Perl I/O (v2.1)

  14. Filehandles • Once created, the file handle can be read from using the diamond operator open PASSWD, “/etc/passwd”; while (<PASSWD>) { chomp; if (/^root:/) { # found root entry # hack hack hack } } • Use print or printf to write/append to a file handle print LOG “Captain’s log, stardate 3.14159\n”; Regular expression Filehandle PLC - Perl I/O (v2.1)

  15. Filehandles • A common way to handle bad file streams: “Open this file or die!” open LOG, “>>logfile” or die “Cannot create logfile: $!”; Cannot create logfile: Permission denied at line 1. $!has the most recent system error message PLC - Perl I/O (v2.1)

  16. File tests Does the file exist? -e $filename Is the file a text file? -T $filename How long ago (in days) was the file last modified? -M $filename How long ago (in days) was the file last accessed? -A $filename How big is the file (in bytes)? -s $filename Is this a directory? -d $filename foreach my $filename (@files) { if –s $filename > 100_000 and –A $filename > 90 { push @big_old_files, $filename; } } PLC - Perl I/O (v2.1)

  17. Perl Standard modules provide methods for dealing with file names and directory structures in a system-independent way: • use File::Spec; # Standard Perl module • Common file path and directory operations, for example: • catfile() -- concatenate directory names and a filename to form a complete path ending with a filename $path = File::Spec->catfile( @directories, $filename ); • curdir() -- returns a string representation of the current directory path $curdir = File::Spec->curdir(); • updir() -- returns a string representation of the parent directory. $updir = File::Spec->updir(); • use File::Find; # Standard Perl module • Traverse a directory tree. • find() -- does a depth-first search over the given @directories in the order they are given. For each file or directory found, it calls the &wanted subroutine. find(\&wanted, @directories); PLC - Perl I/O (v2.1)

  18. Globbing for files • Use the glob operator to search for qualifying files • my @all_files = glob "*"; • Like the ls command • my @pl_files = glob "*.pl"; • Like the command: ls *.pl • A glob will remind you of a regular expression, but regular expressions are different. PLC - Perl I/O (v2.1)

  19. Getting Output from Other Programs • To execute a system command and read the input into a perl program, use the backtick (left apostrophe `) my $date = `date`; my @files = `ls –l`; PLC - Perl I/O (v2.1)

  20. Revision History • Revision History • v1.00, 10/16/2003 11:29 AM, sps Initial revision. • v1.01, 1/21/2004 12:56 PM, sps Filehandle stuff added. • v1.02, 4/14/2004 9:12 AM, sps 20033 updates. • v1.03, 10/18/2004 9:17 AM, sps 20041 updates. -- v2.0, 1/17/2005, chr -- v2.1, 2/14/2007, chr added information re. Perl Standard Modules PLC - Perl I/O (v2.1)

More Related