Perl programming

68
RAHIM AHMEDOV PERL Programming

description

Perl programming

Transcript of Perl programming

Page 1: Perl programming

RAHIM AHMEDOV

PERL Programming

Page 2: Perl programming

CONTENTS

Introduction to Perl Programming languageScalarsControl structuresArraysHashesBasic I/ORegular expressionsFilehandles and filesSubroutines and modulesFile and directory operationsReferences

Page 3: Perl programming

PERL PROGRAMMING LANGUAGE: Intro

PERL is for Practical Extraction And Report Language

Perl advantages: Combines shell script languages, Unix commands like

awk, sed, grep, sort, tr, include C library routines and system calls

Faster than shell scripts: perl interprets the commands, convert them in to platform independent byte code and then execute

Safer than C.

Page 4: Perl programming

PERL PROGRAMMING LANGUAGE: Basics

Statements Use “;” as statement separator

Comments “#” use to comment the line “#!” identify the path that is used to compile and execute the

code. Appears at 1st line Printing

Use print command: print “Hello world”;Variables

Scalar variables: variable that contain single value. Scalars are identified by placing “$” before variable name:

$x = 10; $x = “ten”;

Simple operators Simple numeric operators: +, -, *, %, /, ** (exponential)

Page 5: Perl programming

PERL PROGRAMMING LANGUAGE: Running script

Ways to run perl script: perl filename chmod +x filename; ./filename

Perl command line options: -e: execute perl statement:

perl –e ‘print “hello world”’ -w: display warnings. -c: check syntax of script without executing it -n: loop through the specified file, applying command

or script for each line, as awk. perl –ne ‘print’ records.dat

-v, -V: version information

Page 6: Perl programming

SCALARS

Initializing and assigning values in perl is straightforward: $a = 1; $b = 3.14; $c = “String”; $d = undef;

undef is equivalent of null Perl allows uninitialized variables. Perl decides by

operator whether data is numeric or string $var = 15;

$var = $vrr +1;print $var;

If –w is used, perl check for 3 things: Variables that are used only once Subroutines that are defined 2nd time Syntactically correct but suspicious constructions

Page 7: Perl programming

SCALARS: Scalar data

Numeric data: 2.5, -1.5e11, 1_000_000, 021 (octal), 0xaf, 0b1110011

String data: perl use to quotation for string Single quotation (strong quote): all characters are taken

literally. No character conversion nor variable interpolation is done: $var = “world”;print ‘hello $var\n’; Output: hello $var\n $>

Double quotation (weak quotes): all special characters are converted and variable interpolation is done: print “hello $var\n”; Output: hello world$>

Quoting operators; Single quote operator: q/string/

print q/hello $var\n/; Double quote operator: qq/string/

print qq/hello $var\n/;

Page 8: Perl programming

SCALARS: Operators

Arithmetic operators assignment operators:

= , +=, -=, *=, /=, **=, %= Autoincrement and autodecrement operators

$a++, ++$a, $a--, --$a

Bitwise operators &, |, ^, >>, <<

Boolean expression If expression is undef or 0 it is false If expression is not undef or 0 it is true

Page 9: Perl programming

SCALARS: Comparison operators

Numeric operator String operator

Meaning

> gt Greater than

< lt Less than

>= ge Greater than or equal

<= le Less than or equal

== eq Equal to

!= ne Not equal to

<=> cmp Boolean equality operator. $a = (3 <=> 2); #$a is 1$a = (3 <=> 3); #$a is 0$a = (3 <=> 4); #$a is -1

Page 10: Perl programming

SCALARS: Logical operators

Symbol Word Meaning

&& and Logical and

|| or Logical or

! not Logical not

^ xor Exclusive or

Page 11: Perl programming

SCALARS: String operators

Function Meaning

. Concatenate 2 string:$a = “hello”;$b = “world!”;$c = $a.$b; helloworld!

x Repeats string several time$c = $a x 2; hellohello

.= $a .= $b; helloworld

x= $a x= 2; hellohello

Page 12: Perl programming

SCALARS: Reading from standard input

To read from standard input predefined filehandle STDIN can be used: $in = <STDIN>;

To remove last character (as the last character is always \n if you read from keyboard) chop and chomp string functions is used. chop(string): modify string by removing last

character of this string chomp(string): modify string by removing last

character of this string if the last character in \n chomp($in = <STDIN>);

Page 13: Perl programming

SCALARS: String functions

Function Meaning

substr(string, start [, length])

Rvalue: $s = substr (…);Returns the substring to right value

Lvalue: substr($s, …) = “A string”;Replaces what would have been returned by function with the value on the right.

length $str Return length of string

reverse $str Returns a string in reversed order

lc $str Return string in lower case

lcfirst $str Return string with the 1st character in lowercase

ucfirst $str Return string with the 1st character in uppercase

ord $str Returns ASCII value of character

chr $num Returns character represented by the ASCII value

Page 14: Perl programming

CONTROL STRUCTURES

if statement: if (condition) {statement_block} if (condition) {statement block} else {statement_block}

if (condition) {statement_block} elsif (condition2) {statement_block}…else {statement_block}

unless statement is same as if statement but block executes when condition is false. print “lets go outside” unless ($isRaining);

Page 15: Perl programming

CONTROL STRUCTURES: Loops

while loop: executes as long as condition is true while (condition) {

statement_block}

until loop: executes as long as condition is false until (condition) {

statement_block}

do loops: do {

statement_block} while (condition);

do {statement_block

} until (condition); for loop

for (initialization; condition; increment) {statement_block} foreach loop

foreach $var (LIST) {statement_block} for $var (LIST) {statement_block}

Page 16: Perl programming

CONTROL STRUCTURES: Heredocs

print <<end_tag;The text goes here …The text goes here ……end_tag

Text between tags is printed out exactly as formatted

Variables are interpolated and escape characters are converted

Back quotas (“``”) can be used to pass content of heredoc to shell for execution

Page 17: Perl programming

CONTROL STRUCTURES: Statement modifiers

statemet if condition; print “$a world!\n” if $a eq “hello”;

statemet unless condition;statemet while condition;statemet until condition;statemet for condition;

Page 18: Perl programming

CONTROL STRUCTURES: Loop control

next loop control: skip the rest of the block and begin the next iteration for ($i=0;$i<=10;$i++) {

print “$i “; next; print $i*10; } Output: 0 1 2 3 4 5 6 7 8 9 10

redo loop control restart current iteration for ($i=0;$i<=10;$i++) {

print “$i “; redo; print $i*10; } Output: 0 0 0 0 0 0 …

last loop control exit the loop for ($i=0;$i<=10;$i++) {

print “$i “; last; print $i*10; } Output: 0 1 2 3 4 5 6 7 8 9 10

Page 19: Perl programming

CONTROL STRUCTURES: Labels

Labels are written in upper caseLoop controls are used as goto statement

$i = 1;TOP: {

print “$i “;$i++;last TOP if $i == 10;redo TOP;print “got here”;

}print “goodbye…\n”;

output: 1 2 3 4 5 6 7 8 9 goodbye…

Page 20: Perl programming

ARRAYS

Array variable names start with @ @arr = (1, 2 , 3, 4, 5, 6, 7, 8);

Arrays are named listsLists are constructed by putting comma

separated scalars between parentheses (1, 2, 3, 4, 5, 6) (11, 13, “One”, “Two”) (12, 14, undef, “three”) List as the range of value: (1 .. 5) Empty list: ()

Page 21: Perl programming

ARRAYS: Initialization and access

Array do not have to be declaredArray definition examples:

@arr1 = (1, 2, 3, 4, 5, 6); @arr2 = (11, 13, “One”, “Two”); @arr3 = (12, 14, undef, “three”); @arr4 = (1 .. 5); @arr5 = ();

qw// quoting operator can be used if array contains string data. qw// does not perform variable interpolation! @arr = (“one”, “two”, “three”, “four”); @arr = qw/one two three four/;

Page 22: Perl programming

ARRAYS: Initialization and access (2)

Accessing single element $a = $arr[0]; $a = $arr[-2]; # accesses the 2nd to last element

Getting last index of an array $lst = $#arr;

Adding elements @arr = (@arr, “last”); # add to end @arr = (“first”, @arr); # add to front

Get the length of an array $len = @arr;

Iterations foreach $elem (@arr) {print $elem}

$_ “the default” variable foreach (@arr) {print $_} # $_ gets the current variable

Page 23: Perl programming

ARRAYS: Flat lists and slices

Lists could be combined. Result is flat list where all elements are sequential@arr1 = (3, 4, 5);@arr2 = (6, 7, 8);@arr = (1, 2, @arr1, @arr2, 9, 10);print @arr;output: 1 2 3 4 5 6 7 8 9 10

Slices: @arr = (“one”, “two”, “three”, “four”, “five”, “six”);

@slice1 = @arr[1, 3]; @slice2 = @arr[0 .. 2]; @arr[1, 3] = @arr[3, 1]; #swap element 2 and 4

Page 24: Perl programming

ARRAYS: @ARGV and multidimensional arrays

@ARGV contains arguments passed on the command line. $ARGV[0] contains 1st command line argument

Multidimensional array initialization @marr = ([1, 2, 3], [4, 5, 6]);

Multidimensional array element access: $x = $marr[1][0];

Page 25: Perl programming

ARRAYS: Array functions

Function Description

shift array Removes 1st element of an array and return this removed element$first = shift @arr;

unshift array Insert element to the beginning of an array, returns array’s new count$cnt = unshift @arr “elem1”;

pop array Removes last element of an array and return this removed element$last = pop @arr;

push array, element Insert element to the end of an array, returns array’s new count$cnt = push @arr “elem”;

Page 26: Perl programming

ARRAYS: Array functions (2)

Function Description

splice array, start_pos [, number, list]

Removes number of elements from array starting from start_pos. if number is not specified, removes till end if element. If LIST is specified, replace removed part with list.splice @arr, 2, 4, @rep_arr;

reverse array Reverse the array’s elements@rev = reverse @arr;

print Print array to output

print @arr;

grep reg_exp, array Returns matched to reg_exp elements of array.@narr = grep /^a/, @arr;

Page 27: Perl programming

ARRAYS: split and join

split function splits string into substrings and return it to array. Regular expression, string or single characters can be a separator: @passwd = split /:/, $passwd;

If separator is “//” each character is spitted into array: @chars = split //, “abcdefgh”; Output: a b c d e f g h

To split and remove leading white spaces single quote (“‘ ‘” ) is used: $str = “ a b c”; @chrs = split / /, $str; #output: chrs[0]= “ “, chrs[1]=a,

# chrs[2]=“ “, chrs[3]=b, chrs[4]=c @chrs = split ‘ ‘, $str; #output: chrs[0]=a, chrs[1]=b,

# chrs[2]=c Join joins elements of an array into string:

$str = join “::”, @words;

Page 28: Perl programming

ARRAYS: sorting

sort function by default sorts in ASCII order. @sortarr = sort @arr;

Sort logic used in sort function can be customized: String sort:

@sarr = sort {$a cmp $b} @arr; $a and $b is special variables which represents 1st and 2nd

elements String sort descending order:

@sarr = sort {$b cmp $a} @arr; Numeric sort:

@sarr = sort {$a <=> $b} @arr; @sarr = sort {$b <=> $a} @arr;

Complex example: @sarr = sort {$a <=> $b || $a cmp $b} @arr;

Page 29: Perl programming

HASHES

Hashes are associative array, which is organized as key => value pair.

Hashes are represented by %Hash initialization example:

Define using key => value %emp = (“name” => “john”, “sname” => “hodson”, “position”=> “team member”);

Define using array like syntax %emp = (“name” , “john”, “sname” , “hodson”, “position”, “team member”);

Accessing hash elements: $emp_name = $emp{“name”};

Special hash variable %ENV contains environment variables: $path = $ENV{PATH};

Page 30: Perl programming

HASHES: Hash functions

keys returns all keys in hash into array @k = keys %emp; $k = keys %emp; #return number of keys Keys are in random order.

values returns all values in hash into array @v = values %emp; $v = values %emp;

each returns one key and one value in every call ($k, $v) = each %emp;

reverse change values to keys, keys to values: %rev = reverse %emp;

Page 31: Perl programming

HASHES: iterations and sorting

Using for loop with keys function foreach $key (keys %emp) {

print “$key -> $emp{$key}\n”; } foreach (keys %emp) {

print “$_ -> $emp{$_}\n”; }Using while loop with each function

while ( ($k, $v) = each %emp) {print “$k -> $v\n”; }

Sorting by the keys: foreach $key (sort keys %emp) { print “$key->$emp{$key}\n”; }

Page 32: Perl programming

HASHES: Adding, removing and testing

Adding elements: %emp = (“name” => “John”, “sname” => “Hodson”, “position”=> “team member”)$emp{payroll} = “0888”; # add new key payrol

# with value 0888Deleting elements:

undef $emp{name}; # value set to “” or undef delete $emp{payroll}; # payroll key deleted

Checking existence and if defined print “exists” if exists $emp{payroll}; print “defined” if defined $emp{name};

Hash slices: @emp{“name”, “position”} = (“rahim”, “team member”); As hash slices is a list @ is used.

Page 33: Perl programming

BASIC I/O

<> filehandle can be used to read file or files from command line: #!/usr/bin/perl -w

# reader.plwhile (<>) { print ; }

$> ./reader.pl data.txt data2.txt Formatted output

printf can be used to format output: printf [FILEHANDLE] FORMAT, LIST; printf “%15s %5d %4.2f\n”, “a”, 5, 5.1;

Commonly used formats: d decimal integer f floating point format s string - left justified + right justified

sprintf can be used to print into string:$str = sprintf FORMAT, LIST;

Page 34: Perl programming

BASIC I/O: Page formats

format keyword is used for defining page formats: format FILE_HANDLE_NAME =

picture lines[argument lines].

format STDOUT =@<<<<<<<< @<<<<<<<<<<<< @##### @##### @###.##$$host, $ip, $kbin, $kbout, $costs.

Placeholder descriptions @<<<<: left justified field with fixed length @>>>>: right justified field with fixed length @||||: centered fields with fixed length @###.##: right justified numeric field with fixed length and optional decimal

point @*: multiline field ^<<<, ^>>>, …: fields that start with ^ are successively filled up with the

text of variable. For defining page header format “_TOP” is added to

FILE_HANDLE_NAME

Page 35: Perl programming

BASIC I/O: printing using page formats

write is used to print data in desired page format. write [FLHANDLE]; #if FLHANDLE is omitted it prints to STDOUT

Example:open FORM1, "<$ARGV[0]";format STDOUT =@<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @####### @########

@#####.####$$host, $ip, $kbin, $kbout, $costs.format STDOUT_TOP =Hostname IP Address KByteIN KByteOUT Cost===============================================================. while (<FORM1>) { ($host, $ip, $kbin, $kbout, $costs) = split ' ', $_;

write ; }

Page 36: Perl programming

BASIC I/O: Changing format of filehandle

select is used to select filehandle as standard select FORM1; write;

$~ is standard output filehandle format: $~ = FORM1;

$^ is standard output filehandle header format: $^ = FORM1_TOP;

Special variables for page formats: $%: current page number $=: number of lines per page $-: number of lines remaining on the page

Page 37: Perl programming

REGULAR EXPRESSIONS

Binding operator (=~) and matching operator (m// or //) is used for string search and matching if ($line =~ m/text/) { print “matches”; } Opposite of =~ is !~ (not matches)

Working with $_: while (<>) {

if ($_ =~ /ab/) {print $_;

} }

while (<>) {if (/ab/) {

print ;}

}

Page 38: Perl programming

REGULAR EXPRESSIONS: single-char patterns

Character Description

. Any character:/a.b/

[…] Builds a character class. Any character found in class return a true/[a-zA-Z]/, /[abs1-0]/

[^…] Any character found in class return false./[^a-zA-Z]/, /[^abs1-0]/

\ Escape character. /[0-9]\+[0-9]/

| Or operator for regular expression/bc|ef/

Page 39: Perl programming

REGULAR EXPRESSIONS: Default character class

Predefined character

Character class

Negated characters

Character class

\d [0-9] \D [^0-9]

\w [a-zA-Z0-9_] \W [^a-zA-Z0-9_]

\s (white space)

[ \r\t\n\f] \S [^ \r\t\n\f]

Page 40: Perl programming

REGULAR EXPRESSIONS: Anchors

Anchor Description

^ The beginning of the line/^a6/

$ The end of line/..c$/

\b A word boundary. To delimit a word put \b in the front and at the end of pattern/ab\b/

\B Opposite of \b

Page 41: Perl programming

REGULAR EXPRESSIONS: Quantifiers

Quantifier

Description

* The previous character is repeated 0 or more time/a5555*/

+ The previous character is repeated 1 or more time/a5555+/

? The previous character must appear exactly one time or not at all/a5?\D/

{n} The previous character exactly appears n times/a5{4}\D/

{m,n} The previous character appears from m to n times/a5{3,5}\D/

{m,} The previous character appears m or more times/a5{3,}\D/

(..) This groups characters together for use in alteration/(ab){2}/

Page 42: Perl programming

REGULAR EXPRESSION: Capturing & back referencing

To mark substring () is used. To reference matched part $1..$N is used: while (<>) {

/(.*):.*:.*:.*:(.*):.*:.*/;$login = $1; $comment = $2; }

Inside the regular expression pattern can also be back reference to matched parts. \1..\N is used as reference: /\w+i(ss)i\1/ matches:

MississippiGreediness is property of regular expression, where

patterns always try to match the largest possible part of a string $str = “In a galaxy far, far away”;if ($str =~ /(f.*r)/) {print $1}Result: far, far

Page 43: Perl programming

REGULAR EXPRESSION: Special variables

Variable Meaning

$& Contains matching part of the whole string

$` Contains left part of the string (before matching position)

$’ Contains right part of the string (after matching position)

$+ Contains the last match in parentheses

Page 44: Perl programming

REGULAR EXPRESSION: Substitute operator

s/// operator replace matching string with new string $str =~ s/match/replacement/;

Modifiers: i modifier makes search case insensitive:

$str =~ s/match/replacement/i; g modifier replaces all matched string. By default s

only replaces 1st match $str =~ s/match/replacement/g;

Page 45: Perl programming

REGULAR EXPRESSION: Translation operator

tr/// is used for translation $str = “abcdabcd”;

$str =~ tr/a/A/; #makes a uppercase Modifiers for translation:

s modifier removes consecutive repeating characters from a string $str = “aaaabbbbccccdddd”;$str =~ tr/a-z/a-z/s; # $str is abcd

c modifier tells tr to replace any character not included in 1st list with the character in 2nd list $str = “abc def”; $str =~ tr/a-z/_/c; # $str is abc_def

If the length of the 2nd list does not match the 1st, the last character in the 2nd list will replace any characters in the 1st beyond it. $str = “abcdabcdefgh”; $str =~ tr/a-z/a-c/; # $str is abccabcccccc

Page 46: Perl programming

FILEHANDLES & FILES

Opening files: open FH, “filename”; for reading: open FH, “<filename”; for writing, truncates the file: open FH, “>filename”; for appending: open FH, “>>filename”;

die function can be used error handling. It prints error message and exit program open FH, “<filename” or die “error! ”;

$! variable stores generated error message open FH, “<filename” or die $!;

Closing file handle close FH;

Page 47: Perl programming

FILEHANDLES & FILES: Reading from file

<FILEHANDLE> is used for reading files: while ($ln = <FH>) { print $ln; } while (<FH>) { print $_;}

Reading file into array @lines = <FH>; # slurp file into array

DATA is predefined filehandle for reading data from script file itself. Data is denoted by the marker __END__ @line = <DATA>;foreach $ln (@line) {

print $ln; }__END__Data1 data2Data3 data4Data5 data6

Page 48: Perl programming

FILEHANDLES & FILES: Writing to file

Print is used to write into filehandle open FH, “>filename”print FH “data”;

$, and $\ is used to modify print $, define separator between elements $\define trailing character$, = “--”;$\=“\n”;print “aa”, “bb”;print “cc”, “dd”;

Output: aa--bbcc--dd

Page 49: Perl programming

FILEHANDLES & FILES: Processes & system commands

Using back quotes to start external commands: @lists = `who |grep sa`;

Using qx// to start external commands: @lists = qx/who |grep sa/;

Using system to start external command: system “date”; system “ping –s $host” and die “Command failed\n”;

Using filehandels: open LS, “ls –l |”; while (<LS>) {print ;} # same result as ls –l

Piping can be also used to write to another process open IN, “<file”;open OUT, “| wc”;while (<IN>) { print OUT; }

Page 50: Perl programming

SUBROUTINES & MODULES

Subroutines are defined using sub keyword sub subroutine {

statement;statement;

}Valid invocation forms:

subroutine(); &subroutine(); &subroutine; subroutine;

To define return value return is used: sub subroutine {

statement;return value;

}

Page 51: Perl programming

SUBROUTINES & MODULES: Passing parameters

When subroutine executes, the passed parameters are available in the special array @_. So no need for defining parameters when subroutines are declared: sub myuc{

$_[0] = uc ($_[0]);return $_[0];

}As the values stored in @_ are references to original

values, by default parameters are passing by reference.

Defining subroutine prototype: sub add($$);sub add {

return $_[0] +$_[1];}

Page 52: Perl programming

SUBROUTINES & MODULES: Scope

By default all variables are global variables: $name = “Larry”;

$ret = myuc($name);print $copy_name;sub myuc{

$copy_name = $_[0]; $copy_name = uc($copy_name);return $copy_name; } output is LARRY

my is used to declare local variables. my variables have meaning only within the code block, where they are defined my $var;

local variables are broadened than my: they are also visible in subroutines called from within the block in which they are declared: sub printall {

local $car = “fiat”;printcar(); }

sub printcar { print $car; } output is fiat

Page 53: Perl programming

SUBROUTINES & MODULES: Pragmas & context sensitivity

Pragmatic modules or pragmas gives the compiler hints how to handle the code. use strict; Strict pragma requires all variables in a script be declared as

my or as explicitly specify global variablesA context-sensitive subroutine returns the correct

data type whether it is in a scalar or list context. To implement context sensitivity wantarray is used: sub mysplit{

my $str = $_[0];my @list = split /:/, $str;my $len = @list;return @list if wantarray();return $len;

}

Page 54: Perl programming

SUBROUTINES & MODULES: Libraries

Libraries are an older way of sharing subroutines Libraries should return true Creating library:

# mymath.plsub add { return $_[0]+$[1]; }sub substract { return $_[0]-$[1]; }sub mult { return $_[0]*$[1]; }1;

@INC array is searched by Perl for libraries and modules to include in script.

require is used to include library: use strict;

unshift @INC, “$ENV{HOME}/myPerlLibs”;require “mymath.pl”;my $x = 2; my $y = 3;my $sum = &add($x, $y);

Libraries do not have own namespace. So subroutines declared in libraries must be unique.

Page 55: Perl programming

SUBROUTINES & MODULES: Packages

Packages store variables and subroutines in different namespaces Packages should return true; package is used to declare packages:

# mymath.plpackage mymath;sub add { return $_[0]+$[1]; }sub substract { return $_[0]-$[1]; }sub mult { return $_[0]*$[1]; }1;

For using package variables and subroutines namespace name (packname::) should be prefixed on variable and subroutine names use strict;

unshift @INC, “$ENV{HOME}/myPerlLibs”;require “mymath.pl”;my $x = 2; my $y = 3;my $sum = &mymath::add($x, $y);

Perl has default namespace for all scripts: main:: $main::sum = &mymath::add($x, $y); # Here $main::sum becomes global variable

Page 56: Perl programming

SUBROUTINES & MODULES: Modules

Packages and libraries are included at run time, but modules are included at compile time.

Modules are defined in the same way as packages, but with extension .pm

use is used to include module in script. It includes file at compile time.

BEGIN{..} block is executed during compile time use strict;

BEGIN { unshift @INC, “$ENV{HOME}/myPerlLibs”; }use mymath;my $x = 2; my $y = 3;my $sum = &mymath::add($x, $y)

BEGIN { unshift @INC, “$ENV{HOME}/myPerlLibs/”; } can be replaced by use lib: use lib “$ENV{HOME}/myPerlLibs/”;

END{..} block is executed after end of program (even if program exits with die)

Page 57: Perl programming

FILE & DIRECTORY OPERATIONS

Perl offers special file and directory test operators like UNIX shells:

General file and directory operators:

Operator Meaning

-A The access age in days

-b File is block-special file

-B File is binary

-c File is character-special file

-C Inode modification age in days

-d File is directory

-e File or directory exits

-f File is a plain file

-g File or directory have setgid

Page 58: Perl programming

FILE & DIRECTORY OPERATIONS:General file & directory operators(2)

Operator Meaning

-k File or directory has sticky bit set

-l Entry is symbolic link

-M Modification age in days

-p Entry is named pipe

-s File or directory exits and has non-zero size. Also returns file size

-S The entry is socket

-T The entry is text

-u File has setuid

-z File exits and has zero size

Page 59: Perl programming

FILE & DIRECTORY OPERATIONS: File & directory tests

Example: $file = “file”;if (-d $file) {

print “$file is directory\n”$age = -M $file;

}Perl use _ to access the inode information from the

last call. $file = “temp.pl”;-e $file or die “File doesn’t exists\n”;-w _ or die “File doesn’t have writable access\n”;

stat function retrieves complete list of inode contents: ($dev, $inode, $mode, $nlink, $uid,

$gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks) = stat $file;

Page 60: Perl programming

FILE & DIRECTORY OPERATIONS: Permissions

Operator Meaning

-o File or directory is owned by user

-O File or directory is owned by real user

-r File or directory is readable

-R File or directory is readable by real user

-w File or directory is writable

-W File or directory is writable by real user

-x File or directory is executable

-X File or directory is executable by real user

Page 61: Perl programming

FILE & DIRECTORY OPERATIONS: Reading directory contents

Using UNIX commands @dir = `ls`; @dir = `ls -l`; @dir = qx/ls –l *.txt/;

Using file-name globbing, <> is used for globbing for (<./*>) {

print “$_ \n”; } for (sort <$dir/*.pl>) {

print “$_ \n”; }Using directory handles. Directory handle

functions are not a filehandle and has its own namespace open DH, “dirname”;for (sort readdir (DH)) {

if (/\.pl/) {print “$_\n”;} }

Page 62: Perl programming

FILE & DIRETORY OPERATIONS: File & directory functions

Function Meaning

opendir DH, “dirname”; Open a directory handle

readdir DH; Reads one entry from the directory handle DH

telldir DH; States the position of the pointer to DH

seekdir DH, pos; Sets the pointer to DH to the specific position

rewinddir DH; Sets the pointer to DH to the beginning

closedir DH; Closes DH

unlink filename; Deletes a file

rename oldfile, newfile; Renames a file or directory

link oldfile, newfile; Creates a hard link

symlink oldfile, newfile; Creates a symbolic link

Page 63: Perl programming

FILE & DIRETORY OPERATIONS: File & directory functions (2)

Functions Meaning

readlink linkname; Returns the path and file pointed to by the link

mkdir dirname, perms; Create new directory

rmdir dirname; Deletes empty directory

chdir dirname; Change the current directory

chown uid, gid, filename; Change file owner

chmod perms, filename; Change permission of file

utime atime, mtime, filename; Changes access and modification time

Page 64: Perl programming

REFERENCES

References in Perl are creating by putting \ in front of variable

Creating references to named: $str = “String”;$sref = \$str;

Creating references to anonymous variables $sref = \”String”;

To get access to data a reference points to, the reference must be dereferenced: $str = “String”;$sref = \$str;print ${$sref};${$sref} = “Newstr”; # $str become “Newstr”

New value cannot be assigned to references of anonymous variables!

Page 65: Perl programming

REFERENCES: References to array

Creating reference to named array: @arr = (“elem1”, “elem2”);

$aref = \@arr; Creating reference to anonymous array: [] is used

@aref = [“elem1”, “elem2”]; \(“elem1”, “elem2”) is equivalent to (\”elem1”, \“elem2”) and will just

return list of two scalar references Dereferencing array references:

@new = @{$aref};print ${$aref}[1];

-> operator is also used for dereferencing array and hash references print $aref->[1];

Arrays can be passed by reference to subroutine, to keep their structure: func(\@a, \@b);

sub func{my ($aref, $bref) = @_;print $aref->[1], $bref->[1]; }

Page 66: Perl programming

REFERENCES: References to hashes

Creating reference to named hash: %hash = (“key1”=>”value1”, “key2”=>”value2”); $href = \%hash;

Creating reference to anonymous hash: {} is used $href = {“key1”=>”value1”, “key2”=>”value2”};

Dereferencing hash references: %new = %{$href}; print $href ->{key1};

Page 67: Perl programming

REFERENCES: Other references

References to subroutines: Create reference to named subroutine

$fref = \&myfunc; Create reference to anonymous subroutine

$fref = sub {print “I hate $_[0]”} ; Dereferencing :

&{fref}($x); $fref->($y);

Reference to filehandles is used if filehandles have to be passed to subroutines. Filehandle is prefixed by (*) $fhref =\*FH; print $fhref “something”;

Reference to refenece $str = “abcd”; $ref = \$str; $rref = \$ref;

print ${${$rref}}; # prints abcdprint $$$rref; # the same

Page 68: Perl programming

REFERENCES: Complex data structures

References make it possible to build complex data structures Arrays of arrays – multidimensional arrays:

@marr ([1,2],[3,4],[5,6]);$a = ${$marr[2]}[0];$a = $marr[2]->[0];$a = $marr[2][0]; #all the same

Hashes of arrays %hash = (key0=>[1,2,3], key1=>[4,5,6]);

print $hash{key1}[1]; Arrays of hashes

@arr = ({“key0”=>”val0”, “key1”=>”val1”}, {“key0”=>”val3”, “key1”=>”val4”});

print $arr[1]{key1}; Hashes of hashes

%hash = (“key0” =>{“keya0”=>”vala1”, “keya1”=>”vala2”}, “key1”=> {“keyb0”=>”valb1”, “keyb1”=>”valb2”});

print $hash{key1}{keyb1};