1 / 28

Perl Training

Agenda . Homework ReviewClass Stuff (I got lazy this week)Homework!!!. Homework. Show us your program. Opening Files. open(HANDLE, FILENAME);Opens FILENAME file, and returns HANDLE for your use.Explicit paths are required for files, so if it's not in the current directory, give the path explici

xenon
Télécharger la présentation

Perl Training

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. Perl Training Files

    2. Agenda Homework Review Class Stuff (I got lazy this week) Homework!!!

    3. Homework Show us your program

    4. Opening Files open(HANDLE, FILENAME); Opens FILENAME file, and returns HANDLE for your use. Explicit paths are required for files, so if its not in the current directory, give the path explicitly, or to be safer, always do. open(INFILE, sample.txt); $theFile = /usr/local/sysadm/vacation.txt; open(INFILE, $theFile);

    5. File Modes To Read a file, use < To write a file, use > To append a file, use >> open(INFILE, <sample.txt); # For reading, read only open(INFILE, sample.txt); # Also for reading open(INFILE, >sample.txt); # For writing, destroying contents open(INFILE, >>sample.txt); # For appending, writes to end of file $theFile = >sample.txt; # Prepare for writing open(INFILE, $theFile); # Open for writing

    6. Did it really open it? The open statement returns true if the open was successful. For reading, open returns true if the file exists and is readable. For writing or appending, open returns true if the file can be written to. If the file exists, it must not be set read only in the operating system. A file does not have to exist to be written to, but you have to have write permission in the directory youre creating the file in. If it doesnt work, it returns false. Possible Usage: open(INFILE, sample.txt) or die Unable to open file;

    7. Using and Closing Files open(ORIG, original.txt) or die Unable to open input; open(NEW, >new.txt) or die Unable to open output; while(<ORIG>) { $theLine = $_; print NEW $theLine; } You should close files when youre finished: close(FILEHANDLE); close(ORIG); close(NEW);

    8. Reading from a text file while(<INFILE>) # <INFILE> returns one line of text at a time including line feed, { # returning true if there is more lines to the file, false otherwise ... } # Program to print a file # Array context open(A, somefile.txt); open(A, somefile.txt); while(<A>) { print $_; } @allLines = <A>; print @allLines; while(<A>) while($line = shift(@allLines)) { { $theLine = $_; print $line; chomp($theLine); } ... }

    9. Writing Text to a file print HANDLE LIST; printf HANDLE FORMAT LIST; open(OUT, >lineout.txt) or die Unable to open output; for($i=0; $i<=10; $i++) { print OUT This is line $i\n; } for($i=11; $i<=20; $i++) { printf OUT This is line %.2d\n, $i; }

    10. Writing to files open(OUT, sample.txt) or die Unable to open...; select(OUT); for($i=21; $i<=30; $i++); { printf This is line %.2d\n, $i; } # Select returns the handle youre replacing $tempHandle = select(OUT); ... select($tempHandle) ... # Select is basically a bad idea, dont do it unless really needed

    11. Testing Files You may want to test conditions about a file before opening it if(-e $file) { open(FILE, $file); } else { print $file does not exist\n; }

    12. File Tests

    13. Stat function Stat (use lstat to get info on file that it is linked to) function returns a whole bunch of information on a file. @info = stat($filename); $info[0] ID of device containing a directory entry for this file $info[1] Inode number $info[2] File Permission Mode $info[3] Number of links $info[4] User ID of the files owner $info[5] Group ID of the files group $info[6] ID of device. This is defined only for character of block special characters $info[7] File size in bytes $info[8] Time of last access in seconds since the epoch (UNIX Timestamp format) $info[9] Time of last modification in seconds since the epoch $info[10] Time of last status change in seconds since the epoch $info[11] Preferred I/O block size. Valid only on BSD type systems $info[12] Number of blocks allocated for the file. Valid only on BSD type systems. my $perms = (stat ($filename))[2] & 07777; printf The octal permissions on $file are %o\n, $perms; # prints ... are 644

    14. Predefined Files Standard File In (STDIN) # Usually the keyboard Standard File Out (STDOUT) # Usually the monitor Standard Error (STDERR) # Depends on # implementation $getLine = <STDIN>; # Waits for you to type # something and assigns # it to $getLine print STDERR Bad User input\n; # Prints to Standard # Error

    15. Pipes open(UPIN, uptime |); # Run the uptime command and take its STDOUT # output and feed it into the UPIN file handle $uptimeInput = <UPIN>; open(LSIN, ls -l /tmp |); while(<LSIN>) { $theLine = $_; chomp($theLine); if(substr($theLine, 0, 1) eq d) { $lastSpace = rindex($theLine, ); $dirName = (substr($theLine, $lastSpace +1)); print $dirName is a directory\n; } }

    16. Pipes (Cont.) $MTo = sysadmin@vservers.com; $MSubject = Data for the script; open(MAIL, | mail -s $MSubject $MTo); print MAIL <<EOF; The name of the file is $file. The size of the file is $size. EOF The rule for pipes in open statements is that piping data to a program (writing) the pipe is on the left of the command. For getting data from a program (reading) the pipe is on the right of the command.

    17. Reading and Writing to Binary Files To Read Binary Files: read(HANDLE, VARIABLE, LENGTH, POSITION); Ex: binmode(FILE); # Forces binary reading $count = read(FILE, $tmp, 50, 0); # Reads the first 50 bytes of FILE into $tmp # $count is the number of bytes actually read # If $count < 50, you got to EOF

    18. Seek with Files seek(HANDLE, RELATIVEPOSITION, FROMWHERE); seek(FILE, 12, 0); # Move to the 13th byte in a file seek(FILE, 12, 1); # Move forward 12 positions seek(FILE, 0, 0); while(read(FILE, $text, 10)) { # $text will be the next 10 bytes of the file, if there are 10 left } $filePos = tell(FILE); # Tells where youre at in the file

    19. Writing to Binary Files @printThese = (37, 36, 35); foreach $item (@printThese) { print FILE chr($item); } # Prints %$# to FILE handle

    20. Changing things about files rename takes two arguments, the old name and the new name, and returns true if successful unless(rename(somedata.txt, somedata.old)) { print The rename failed\n; } utime allows you to change the last accessed/modified time values for a file (ACCESSTIME, MODTIME, file1, file2...) $Now = time(); utime($Now, $Now, somedata.txt); Delete files with the unlink command. Takes a list of files you want deleted, and returns the number of files deleted. unless(unlink(a.dat, b.dat) == 2) { print One of the files wasnt deleted\n; }

    21. Getting Big Globs of Files A glob in Perl is designated as * @AllPLFiles = glob(*.pl); # Grab all files that end in pl unlink(glob(*.tmp)); # Delete all *.tmp files

    22. Unix Geek Functions chmod(perms, @files) Perms must be in octal form chmod(0644, glob(*.htm)); chmod(0755, tmp.cgi, tmp2.cgi, tmp3.cgi) chown(number, number2, @files) number is UID, number2 is GID chown(1001, 121, glob(*.htm)); link/symlink(existing, link_name) link(/var/master.passwd, passwd) # Same as ln /var/master.passwd passwd symlink(/var/master.passwd, sympasswd) # Same as ln -s /var/master.passwd sympasswd print readlink(sympasswd) # Prints /var/master.passwd

    23. Fun functions with Directories opendir(DOCS, /tmp/docs); # Absolute opendir(DOCS, docs); # Relative opendir(CWD, .); # Opens current directory opendir(PARENT, ..); # Opens .. directory $nextFile = readdir(DOCS); # Returns the next file @AllNames = readdir(DOCS); # Returns an array of all the # files in the directory

    24. Walking through Directories opendir(PWD, .); @AllFiles = readdir(PWD); $TotSize = 0; foreach $name (@AllFiles) { if(-d $name) { next; } # Its a directory $TotSize += (-s $name); }

    25. Creating and Destroying Directories mkdir(name, perms) mkdir(subdir, 0755); rmdir(name); rmdir(subdir);

    26. Homework Problem #1 & #2 Create a program that will open the ~/www/ directory on your VServer. Walk through the directory structure, making sure that all the directories are 755 and files are 644. Create a program that will run a Unix command and do something with the output (use Pipes)

    27. Homework Problem #3 Read a list of files from a text file, and print the permissions, file size, whether they are readable/writable and other usefull file information for each file

    28. Questions?

More Related