Post on 19-Dec-2015
Scripting Languages
Chapter 6 I/O Basics
Input from STDIN
• We’ve been doing so with <STDIN>• $line = <STDIN>• chomp($line);• Same as • chomp($line= <STDIN>);• line input op gives you an undef value when you
reach eof – handy for dropping out of loops• while (defined($line = <STDIN>)) {
print “I saw $line”;}
Shortcut
• We’re reading the input into a variable – checking to see if it’s reached the eof (meaning its defined) – if its defined we run the while loop.
• Inside the loop – we’ll see each line one after another.• Since this is something that is done quite often – Perl
has a shortcut.while (<STDIN>) {
print “I saw $_”;}This only works if you put a line-input operator in the
condition of the while loop.
List context
• The previous examples were evaluated in scalar context
• Now for list context:
foreach (<STDIN>) {
print “I saw $_”;
}
gives you all the remaining lines as a list – each element of the list is one line
What’s the difference
• A while loop in Perl reads a line of input – puts it into a variable – runs the body of the loop.
• Then it goes back to fine another line of input.• A foreach loop --- the line-input operator is being
used in a list context – foreach needs a list to iterate through – so it has to read all the input before the loop starts running.
• For large files – its best to use the while loop for better performance.
Input from Diamond Operator
• < > is another way to read input• it uses invocation arguments to accept input • invocation arguments are command line
arguments• Exp:
– $./myprogram.pl x y z– means to run myprogram and it should process file x
followed by file y and then file z– If you give it no invocation args – program should
process the standard input stream or –x means stdin as well.
Benefits
• you can choose where the program gets its input at run time
• exp: you won’t have to rewrite the program to use it in a pipeline ( more later).
• makes it easy for you to write your programs that work like standard Unix utilities – even on non-Unix machines.
• portability of code
Exp:while ( defined($line = <>)){
chomp ($line);print “It was $line that I saw \n”;
}run this with x, y, z invocation args – It was [a line from file x] that I sawIt was [a line from file x] that I saw-- eof then y – then z -- no break with using the <>
its as if all the files are merged into one.
Same Shortcut
may also use the same shortcut:
while (<>){
chomp;
print “It was $_ that I saw!\n”;
}
Typically used for all of your input – mistake to use it in more than one place in your program.
Unix Invocation Arguments
• Typically, the diamond operator isn’t looking at the invocation args – its works with the @ARGV array.
• It is a special array – preset by Perl interpreter to be a list of command line args.
• When program starts @ARGV is stuffed full of the list of invocation args.
• Use it like any other array – shift things off or foreach through it.
• If list is empty in @ARGV -- <> looks uses STDIN stream – otherwise it uses contents of that array
Tinker with @ARGV
• Exp: process three specific files – regardless of user choice at CL
@ARGV = qw! Monday Tuesday Wednesday !;
while (<>) {
chomp;
print “It is $_ \n”;
}
Output to Standard Output
• print operator takes a list of values and sends them – as a string – to stdout – one after another.
• doesn’t add any extra characters before, after or in between by default.
• perlvar man page gives you more information about changing defaults
• if you want spaces between items and a newline at the end – you have to add them
Output - STDOUT
• $name = “Bob Barker”;
• print “Hello there, $name, did you know that 4*5 is “ , 4*5, “?\n”;
• difference between printing an array and interpolating an array:
• print @array; #print a list of items
• print “@array”; #print a string (containing and interpolated array)
Print Statment
• First print statement -- one item after another no spaces
• Second statement will print exactly one item, which is the string you get by interpolating @array into the empty string – the contents of the array separated by spaces.
Print Cont’d• But what if @array is a list of unchomped lines of input?• Contain trailing newline character• First print statement –
MondayTuesdayWednesdaySecond one:
Monday Tuesday Wednesayit’s interpolating the array so it puts spaces between elements – this is
what happens when you put an array in double quotes
So ….
• So – if your strings contain newlines
print @array;
no newlines
print “@array\n”;
Print Cont’d
• print is looking for a list of strings to print
• its arguments are evaluated in list context
• <> will return a list of lines in list context
• so:
print < >; # similar to the cat command
print sort <>; #similar to Unix sort command
Revisit Parenthesis
print (“Hello, World\n”);
print “Hello, World\n”;
if the invocation of print looks like a function call, then it is a function call
print (5*4); #prints 20 but also contains a return value – true / false
usually always succeeds unless I/O error
Return Value Cont’d
• print (5*4) +3;
• error prints 20 but return value is 1 – 1 + 3 is 4 – logic error.
• If it looks like a function – it is a function
• applies to all Perl functions
Formatted Output with printf
• C’s printf is similar to Perl’s printf
• take a format string followed b a list of things to print
• the format string is a fill-in-the-blanks template with the desired form of output.
printf “Hello, %s; your password expires in %d days!\n”, $user, $days_to_expire;
printf
• conversions begin with %
• should be the same number of items in the list as there are conversions
• don’t match – don’t work
• common conversions:– %s – string, %g – auto chooses int, fp or exp– %d – decimal point – value is truncated not
rounded
printf Cont’d
• field width:– printf “%6d\n”, 42 # - - - -42– printf “%2d\n”, 2e3 + 1.95; #2001
%s – stringit interpolates the given value as a string
printf “10%s\n”, “perl”; # ------perlnegative field left justifies
printf “-15%s\n”, “perl”; #perl-----------
%f
• rounds off its output as needed
• even lets you request number of digits after the decimal pt.
printf “%12f\n”, 6*7 + 2/3; #---42.666667
printf “%12.3f\n”, 6*7 + 2/3; #------42.667
printf “%12.0f\n”, 6*7 + 2/3; #----------43
to print a real % sign use %%
Arrays and printf
• You won’t use an array as an argument to printfmy @items = qw( soap shampoo conditioner);my $format = “The items are: \n” . (“%10s\n” x @items);printf $format, @items;This uses the x operator to replicate the given string a
number of times given by @itemsThat’s 3 in this case – look at our array valuesoutput prints item on its own line – right justified in a ten
character columnWe use @items once in a list context and once in a scalar
context
/exercises
• Perform 2, 3 exercises on page 97