Getting a filehandle - PowerPoint PPT Presentation

About This Presentation
Title:

Getting a filehandle

Description:

Leading whitespace or trailing non-numeric characters, they will be ignored. ... 40788 c527100 Fred Flintstone 95-10-05 c527100. 32685 c565060 Peter Parker 95 ... – PowerPoint PPT presentation

Number of Views:85
Avg rating:3.0/5.0
Slides: 29
Provided by: qian2
Learn more at: https://www.cse.scu.edu
Category:

less

Transcript and Presenter's Notes

Title: Getting a filehandle


1
Getting a filehandle
  • Open for reading
  • open(FILEHANDLE, FILENAME)
  • open(FILEHANDLE)
  • open FILEHANDLE
  • Closing
  • close (FILEHANDLE)
  • close FILEHANDLE
  • Do or die function shows the open file error
  • open(MYFILE,file) die Cant open file\n

2
Getting a filehandle
  • Open for writing or appending
  • open(FILEHANDLE, gtFILENAME)
  • open(FILEHANDLE,gtgtFILENAME)
  • Open for piping
  • the command in the pipe will be executed
  • open (FILEHANDLE, PIPECMD)
  • open (FILEHANDLE, PIPECMD )
  • Examples
  • open(INPIPE,date )
  • today ltINPIPEgt
  • close (INPIPE)

3
ARGV and Null Filehandle
  • When ltgt is used
  • ARGV array is treated as a special filehandle
  • Perl shifts through the array
  • Examples
  • cat f1
  • Hello there. Nice day!
  • cat f2
  • Are you sure about this?
  • cat f3
  • Are you with me?
  • This is kind of hard!
  • perl -e while (ltARGVgt) print f1 f2 f3
  • Hello there. Nice day!
  • Are you sure about this?
  • Are you with me?
  • This is kind of hard!

4
Example
  • !/usr/local/bin/perl
  • name ARGV0
  • open(FILE, ypcat passwd)
  • while (ltFILEgt)
  • chop
  • _at_words split(,_)
  • if words4/name/)
  • print Login id ,words0,\n
  • print Login Shell ,words6,\n

5
File Testing
  • File testing operators
  • -r file true if file is readable
  • -w file true if file is writable
  • -z file true if file is zero in size
  • -f file true if file is a plain file
  • -T file true if file is a text file
  • -B file true if file a binary
  • -t file true if file is opened to a tty

6
Subroutines
  • Args are passed call by reference
  • All variables created within the subroutine are
    global
  • The subroutine is called by
  • subroutine()
  • do subroutine(par1,)
  • Define a routine
  • sub routinenamebody
  • What is _at__
  • a special array used for referencing the formal
    params
  • the elements are _0,_1,

7
Subroutines
  • sub under
  • print The values in the _at__ array are,_at__\n
  • print The first value is _0\n
  • print The last value is ,pop(_at__),\n
  • foreach value(_at__)
  • value5
  • print The value is value\n
  • print Give me 5 numbers
  • _at_n split( ,ltSTDINgt)
  • under(_at_n)
  • print Back in main\n
  • print The new values are _at_n\n

Give me 5 numbers 1 2 3 4 5 The values in the
_at__array are 1 2 3 4 5 The first value is 1 The
last value is 5 The value is 6 The value is 7 The
value is 8 The value is 9 Back in main The new
values are 6 7 8 9 5
WHY?
8
Directories and Files
  • Creating a directory
  • mkdir(DIRNAME,MODE)
  • perl -e mkdir(joker,0755)
  • Other functions
  • rmdir(DIR)
  • chdir(EXPR)
  • chmod(LIST)
  • chown(LIST)
  • opendir(DIRHANDLE, EXPR) attach to filehandle
  • opendir(MYDIR, blahdir)
  • readdir(), telldir(),seekdir(),closedir()
  • opendir(DIR,..) die Cant open !\n
  • _at_parentfiles readdir(DIR)
  • closedir(DIR)
  • foreach file (_at_parentfiles)
  • print file\n

9
System function
  • Take a UNIX command as its argument
  • send the command to the shell for interpretation
  • return control back to calling script
  • system(UNIX COMMAND)
  • perl -e system(cal 10 1997) print Happy
    Halloween!October 1997S M Tu W Th F S1 2
    Happy Halloween

10
Printf
  • Print a formatted strong to a selected file
    handle (STDOUT)
  • Like printf() in C language
  • printf(FILEHANDLE FORMAT, LIST)
  • printf(FORMAT, LIST)
  • printf(The number is s and the number is
    d,John, 345)

11
Stdin
  • Perl uses ltgt input (read) operator
  • get a line from the FILEHANDLE
  • we can use chop to remove the newline \n
  • Examples
  • print What is your name?
  • name ltSTDINgt enclose STDIN with input
    operator
  • print What is your age?
  • age ltgt read using input operator
  • chop (name) remove the \n from the string
  • Read multiple inputs into arrays
  • _at_all ltSTDINgt

12
getc
  • Gets a single character into a string from a file
    or STDIN
  • getc(FILEHANDLE)
  • getc FILEHANDLE
  • getc
  • Examples
  • print Answer y or n
  • answer getc
  • printf(You say s\n,answer)

13
argv
  • _at_ARGV is the argument array
  • !/usr/bin/perl
  • printf(Number of args d\n,ARGV1)
  • print _at_ARGV\n
  • a ARGV0
  • b ARGV1
  • c ARGV2
  • printf(The name of the scripts is s\n,0)
  • printf(Argument s s s\n,a,b,c)

14
Array Functions
  • chop(LIST)
  • chops off last char of each string in the list
  • pop(ARRAY)
  • pops off last element of the array
  • push(ARRAY,X)
  • similar to stack operation
  • join(DELIMITER, LIST)
  • joins the elements of the array into a single
    string and separates each one by the delimiter
  • split(DELIMITER,EXP)
  • splits up a string by some delimiter and returns
    an array

15
Special Arrays
  • The ENV contains environment variables
  • the key is the name of the environment variable
  • the value is what is assigned to it
  • Example
  • foreach key (keys(ENV))
  • printkey\n
  • print Your login name ENVLOGNAME\n
  • pwd ENVPWD
  • print pwd

16
Operators
  • Most of the operators are borrowed from C
  • Mixing data types
  • x 12!! 4\n strings are converted
    into a number
  • print x
  • y ZAP . 5.5 concatenate two strings
  • Output
  • 16
  • ZAP5.5
  • Perl tests whether operator expects string or
    number.
  • If numeric operator, then perl converts string to
    floating point value. Leading whitespace or
    trailing non-numeric characters, they will be
    ignored. Converts to zero if it cant figure out
    what to do.

17
Operators
  • Assignment operators
  • ,,-,ltlt,
  • Relational operators
  • numeric gt,gt,lt,lt,,!,ltgt
  • string gt,ge,lt,le,eq,ne,cmp
  • Logical operators
  • ,,!
  • x ? y z
  • String operators and functions
  • s1 . s2 s1 x num
  • substr(str1,offset,len) length(EXPR)
  • index(str,substr)

18
Conditional Constructs
  • if (expr) block
  • if (expr) block else block
  • if (expr) block elseif (expr) block else
    block
  • unless (expr) block
  • unless (expr) block else block
  • unless (expr) block elseif (expr) block .
  • while (expr) block eval expr before executing
    block
  • until (expr) block
  • do block while (expr) eval expr after
    executing block
  • do block until (expr)

19
Loops
  • for (expr1 exp2 exp3)block
  • foreach var (array) block
  • _ used if var is not present
  • _at_color(red, green, blue)
  • foreach (_at_color)
  • print _
  • _ black
  • print \n_at_color
  • red green blue
  • black black black

20
Command line value and loops
  • Example
  • print "ARGV is the subscript of the ",
  • "last command arg.\n"
  • Iterate on numeric subscript 0 to ARGV
  • for (i0 i lt ARGV i)
  • print "Argument i is ARGVi.\n"
  • A variation on the preceding loop
  • foreach item (_at_ARGV)
  • print "The word is item.\n"
  • A similar variation, using the
  • "Default Scalar Variable" _
  • foreach (_at_ARGV)
  • print "Say _.\n"
  • Demonstration
  • gt perl example5.pl Gooood evening, Class!
  • 2 is the subscript of the last command arg.
  • Argument 0 is Gooood.
  • Argument 1 is morning,.
  • Argument 2 is Class!.
  • The word is Gooood.
  • The word is morning,.
  • The word is Class!.
  • Say Gooood.
  • Say morning,.
  • Say Class!.

21
Standard I/O
  • print STDOUT "Tell me something "
  • while (input ltSTDINgt)
  • print STDOUT "You said, quote input
    endquote\n"
  • chop input
  • print STDOUT "Without the newline
    input endquote\n"
  • if (input eq '') print STDERR
    "Null input!\n"
  • print STDOUT "Tell me more, or D to
    end\n"
  • print STDOUT "That's all!\n"
  • Note 1 The while statement's condition is an
    assignment statement assign the next record from
    standard input to the variable input. On end of
    file, this will assign not a null value but an
    "undefined" value. An undefined value in the
    context of a condition evaluates to "false".
  • Note 2 Data records are by default terminated by
    a newline character "\n" which in the above
    example is included as the last character of
    variable input. The "chop" function removes the
    last character of its argument. Perl 5 introduces
    a "chomp" function that removes the last
    characters of a variable only if they are the
    currently defined end-of-record sequence, which
    is defined in the special variable /.

22
File I/O
  • !/usr/local/bin/perl
  • Function Reverse each line of a file
  • 1 Get command line values
  • if (ARGV !1)
  • die "Usage 0 inputfile outputfile\n"
  • (infile,outfile) _at_ARGV
  • if (! -r infile)
  • die "Can't read input infile\n"
  • if (! -f infile)
  • die "Input infile is not a plain file\n"
  • 2 Validate files
  • Or statements "" short-circuit, so that
  • if an early part evaluates as true, Perl
  • doesn't bother to evaluate the rest.
  • Here, if the file opens successfully,
  • we don't abort
  • open(INPUT,"ltinfile")
  • die "Can't input infile !"
  • if ( -e outfile)
  • print STDERR "outfile exists!\n"
  • until (ans eq 'r' ans eq 'a'ans eq 'e'
    )
  • print STDERR "rplc, append,or exit? "
  • ans getc(STDIN)
  • if (ans eq 'e') exit
  • if (ans eq 'a') mode'gtgt'
  • else mode'gt'
  • open(OUTPUT,"modeoutfile")
  • die "Can't output outfile !"
  • 3 read reverse each line, output it.
  • while (ltINPUTgt)
  • chop _ _ reverse _
  • print OUTPUT _,"\n"
  • 4 Done!
  • close INPUT,OUTPUT

23
Pipe I/O and System Calls
  • !/usr/local/bin/perl
  • Report on disk usage under specified files
  • The Unix command "du -sk ..." (on BSD Unix, "du
    -s ...")
  • produces a series of lines
  • 1942 bin
  • 2981 etc
  • listing the K bytes used under each file or
    directory. It doesn't show other
  • information, such as the modification date or
    owner. This program gets du's kbytes
  • and filename, and merges this info with other
    useful information for each file.
  • files join(' ',_at_ARGV)
  • The trailing pipe "" directs command output
    into our program
  • if (! open (DUPIPE,"du -sk files sort -nr
    "))
  • die "Can't run du! !\n"
  • printf "8s -8s -16s 8s s\n",
    'K-bytes','Login','Name','Modified','File'
  • while (ltDUPIPEgt) parse the du info
  • (kbytes, filename) split
  • Call system to look up file info like
    "ls" does
  • (dev,ino,mode,nlink,uid,gid,rdev,
    size,atime,mtime,ctime)

24
Pipe I/O and System Calls (conti.)
  • Call system to associate login name with uid
  • if (uid ! previous_uid)
  • (login,passwd,uid,gid,quota,comment,r
    ealname,dir,shell)
  • getpwuid(uid)
  • previous_uid uid
  • Convert the modification-time to readable
    form
  • (sec,min,hour,mday,mon,myear)
    localtime(mtime)
  • mmonth mon1
  • printf "8s -8s -16s 02s-02d-02d s\n",
  • kbytes, login,
    realname, myear, mmonth, mday, filename
  • while loop
  • Demonstration Output
  • K-bytes Login Name
    Modified File
  • 40788 c527100 Fred Flintstone 95-10-05
    c527100
  • 32685 c565060 Peter Parker 95-10-05
    c565060
  • 24932 c579818 Clark Kent 95-10-06
    c579818
  • 15388 c576657 Lois Lane 95-10-06
    c576657
  • 9462 c572038 Bruce Wayne 95-10-06
    c572038

25
Regular Expressions
  • What is a regular expression (in Perl)?
  • a sequence or pattern of characters that is
    matched against a string of text when performing
    searches and replacements
  • Pattern binding operators
  • var /EXP/
  • true if var contains EXP
  • var !/EXP/
  • !(var EXP)
  • VARs/old/new/
  • substitue
  • name Tommy Tuttle
  • print Hello Tommy\n if name /Tom/
  • print name\n if name ! /Tom/
  • name s/T/M/
  • print name.\n

26
Regular Expressions
  • . match any character except newline
  • a-z0-9 match any single char in set
  • a-z match any single char not in set
  • \d match one digit
  • \D same as 0-9
  • \w match an alphanumeric (word) character
  • \W match a non-alphanumeric character
  • \s match whitespace
  • \S match non whitespace
  • match beginning of line
  • match end of line
  • X? match 0 or 1 X
  • X match 0 or more Xs
  • X match 1 or more Xs
  • Xn,m match at least n but not more than m Xs
  • abc match a,b,c respectively
  • waswerewill match was, were or will

27
m and s operator
  • Searches a string for a pattern match
  • m/pattern/i /pattern/i
  • m is optional, i is case sensitive
  • Substitutions
  • s/old/new/ s/old/new/g
  • g stands for global change on a line
  • Examples
  • cat tmp.file
  • John Doe
  • Jane Doe
  • Frank Smith
  • perl -ne s/Doe/Francois/ print tmp.file
  • John Francois
  • Jane Francois
  • Frank Smith

28
tr and y operators
  • Translates characters on a one-to-one
    correspondence, returns the number of characters
    replaced or deleted
  • tr/oldlist/newlist/ y/oldlist/newlist/ (for
    sed users)
  • ARGV1y/A-Z/a-z/ upper to lowercase
  • cnt tr/// count the stars in _
  • cnt tr/0-9// count the digits
  • tr/a-z/ / replace lowercase chars with space
Write a Comment
User Comments (0)
About PowerShow.com