#!/usr/bin/perl -w ################################### # This Document Explains perl Input/output # facilities. # AAK: Last Modification: # Tue Sep 11 21:52:39 PDT 2012 # ################################# # -w option in first line will turning on the warnings # if no argument is entered, it uses standard input print "@ARGV \n"; # @ARGV is an array that stores the argument passed to the script # as explained before, you can read from standard input via: # $inp = <STDIN>; #"say": is the same as print but with \n at the end: #to use say, you need to load features of perl v5.1: use 5.010; say "Hello!"; #you can format the output using printf: printf "Hello, %s; did you know 2 + 3 = %d !\n", Arman, 5; # %s for string, %d for integer, %g for flexible floating-pint, integer exponential: printf "%g %g %g \n", 7/13, 28**43, 1/(2.34**73.232); printf "%10.30f \n", sqrt(2); printf "%10d \n", 287321; #perl uses STDIN, STDOUT, STDERR, DATA ARGV, ARGVOUT #for file handling, user can also define "file handlers" using open operator: open OUTPUT, ">output.dat"; open LOG, ">>log"; open STH, "STH"; # > >> are linux standard output redirectings # you can check if the opening was sucessfull: if ( ! open INPUTDATA, "mydata.dat" ) { die "opening input data failed: $!" } # die commands exits the program with none-zero status, # $! is human readable error that happend #using diamont operator <> you can read from files: #following will read from all files named in the argument #and for each line will do sth: #to close a filehandle: close STH; #perl will close the filehanldes when it exits, but #it is always good idea to be tidy # you can use warn operator instead of die, just to give warn "this is warning usage"; #you can use the file handle just like build-in ones: while (<INPUTDATA>) { print $_; } print LOG "this is log file created by perl \n"; printf LOG "%d %s \n", 2, line; #or you can change the default output filehandle by select: select LOG; print "another line in log\n"; select OUTPUT; print "this will go to output.dat"; select STDOUT; say "Hello again!"; #one more example, to send standard error to somewhere else: if ( ! open STDERR, ">>./.error_log" ) { die "Can't open error log : $!"; } warn "this warning will not be displayed on the terminal"; warn "warnings are going to .error_log file"; close STDERR; warn "this is gonna go nowhere!"; while (defined($line=<>)) { print $line; }