PDA

View Full Version : >>Perl Basics 3<<



G4M3R
23-03-13, 06:29 PM
Functions


In addition to its operators, Perl has many functions. Functions have a human-readable name, such as print and take one or more arguments passed as a list. A function may return no value, a single value (AKA "scalar"), or a list (AKA "array"). You can enclose the argument list in parentheses, or leave the parentheses off.A few examples:




# The function is print. Its argument is a string. # The effect is to print the string to the terminal.print "The rain in Spain falls mainly on the plain.\n"; # Same thing, with parentheses.print("The rain in Spain falls mainly on the plain.\n"); # You can pass a list to print. It will print each argument. # This prints out "The rain in Spain falls 6 times in the plain."print "The rain in Spain falls ",2*4-2," times in the plain.\n"; # Same thing, but with parentheses.print ("The rain in Spain falls ",2*4-2," times in the plain.\n"); # The length function calculates the length of a string, # yielding 45.length "The rain in Spain falls mainly on the plain.\n"; # The split function splits a string based on a delimiter pattern # yielding the list ('The','rain in Spain','falls mainly','on the plain.')split '/','The/rain in Spain/falls mainly/on the plain.';


Often Used Functions (alphabetic listing)


For specific information on a function, use perldoc -f function_name to get a concise summary.




abs (http://stein.cshl.org/cgi-bin/perlref?func=abs)
absolute value


chdir (http://stein.cshl.org/cgi-bin/perlref?func=chdir)
change current directory


chmod (http://stein.cshl.org/cgi-bin/perlref?func=chmod)
change permissions of file/directory


chomp (http://stein.cshl.org/cgi-bin/perlref?func=chomp)
remove terminal newline from string variable


chop (http://stein.cshl.org/cgi-bin/perlref?func=chop)
remove last character from string variable


chown (http://stein.cshl.org/cgi-bin/perlref?func=chown)
change ownership of file/directory


close (http://stein.cshl.org/cgi-bin/perlref?func=close)
close a file handle


closedir (http://stein.cshl.org/cgi-bin/perlref?func=closedir)
close a directory handle


cos (http://stein.cshl.org/cgi-bin/perlref?func=cos)
cosine


defined (http://stein.cshl.org/cgi-bin/perlref?func=defined)
test whether variable is defined


delete (http://stein.cshl.org/cgi-bin/perlref?func=delete)
delete a key from a hash


die (http://stein.cshl.org/cgi-bin/perlref?func=die)
exit with an error message


each (http://stein.cshl.org/cgi-bin/perlref?func=each)
iterate through keys & values of a hash


eof (http://stein.cshl.org/cgi-bin/perlref?func=eof)
test a filehandle for end of file


eval (http://stein.cshl.org/cgi-bin/perlref?func=eval)
evaluate a string as a perl expression


exec (http://stein.cshl.org/cgi-bin/perlref?func=exec)
quit Perl and execute a system command


exists (http://stein.cshl.org/cgi-bin/perlref?func=exists)
test that a hash key exists


exit (http://stein.cshl.org/cgi-bin/perlref?func=exit)
exit from the Perl script


glob (http://stein.cshl.org/cgi-bin/perlref?func=glob)
expand a directory listing using shell wildcards


gmtime (http://stein.cshl.org/cgi-bin/perlref?func=gmtime)
current time in GMT


grep (http://stein.cshl.org/cgi-bin/perlref?func=grep)
filter an array for entries that meet a criterion


index (http://stein.cshl.org/cgi-bin/perlref?func=index)
find location of a substring inside a larger string


int (http://stein.cshl.org/cgi-bin/perlref?func=int)
throw away the fractional part of a floating point number


join (http://stein.cshl.org/cgi-bin/perlref?func=join)
join an array together into a string


keys (http://stein.cshl.org/cgi-bin/perlref?func=keys)
return the keys of a hash


kill (http://stein.cshl.org/cgi-bin/perlref?func=kill)
send a signal to one or more processes


last (http://stein.cshl.org/cgi-bin/perlref?func=last)
exit enclosing loop


lc (http://stein.cshl.org/cgi-bin/perlref?func=lc)
convert string to lowercase


lcfirst (http://stein.cshl.org/cgi-bin/perlref?func=lcfirst)
lowercase first character of string


length (http://stein.cshl.org/cgi-bin/perlref?func=length)
find length of string


local (http://stein.cshl.org/cgi-bin/perlref?func=local)
temporarily replace the value of a global variable


localtime (http://stein.cshl.org/cgi-bin/perlref?func=localtime)
return time in local timezone


log (http://stein.cshl.org/cgi-bin/perlref?func=log)
natural logarithm


m// (http://stein.cshl.org/cgi-bin/perlref?func=m//)
pattern match operation


map (http://stein.cshl.org/cgi-bin/perlref?func=map)
perform on operation on each member of array or list


mkdir (http://stein.cshl.org/cgi-bin/perlref?func=mkdir)
make a new directory


my (http://stein.cshl.org/cgi-bin/perlref?func=my)
create a local variable


next (http://stein.cshl.org/cgi-bin/perlref?func=next)
jump to the top of enclosing loop


open (http://stein.cshl.org/cgi-bin/perlref?func=open)
open a file for reading or writing


opendir (http://stein.cshl.org/cgi-bin/perlref?func=opendir)
open a directory for listing


pack (http://stein.cshl.org/cgi-bin/perlref?func=pack)
pack a list into a compact binary representation


package (http://stein.cshl.org/cgi-bin/perlref?func=package)
create a new namespace for a module


pop (http://stein.cshl.org/cgi-bin/perlref?func=pop)
pop the last item off the end of an array


print (http://stein.cshl.org/cgi-bin/perlref?func=print)
print to terminal or a file


printf (http://stein.cshl.org/cgi-bin/perlref?func=printf)
formatted print to a terminal or file


push (http://stein.cshl.org/cgi-bin/perlref?func=push)
push a value onto the end of an array


q/STRING/ (http://stein.cshl.org/cgi-bin/perlref?func=q/STRING/)
generalized single-quote operation


qq/STRING/ (http://stein.cshl.org/cgi-bin/perlref?func=qq/STRING/)
generalized double-quote operation


qx/STRING/ (http://stein.cshl.org/cgi-bin/perlref?func=qx/STRING/)
generalized backtick operation


qw/STRING/ (http://stein.cshl.org/cgi-bin/perlref?func=qw/STRING/)
turn a space-delimited string of words into a list


rand (http://stein.cshl.org/cgi-bin/perlref?func=rand)
random number generator


read (http://stein.cshl.org/cgi-bin/perlref?func=read)
read binary data from a file


readdir (http://stein.cshl.org/cgi-bin/perlref?func=readdir)
read the contents of a directory


readline (http://stein.cshl.org/cgi-bin/perlref?func=readline)
read a line from a text file


readlink (http://stein.cshl.org/cgi-bin/perlref?func=readlink)
determine the target of a symbolic link


redo (http://stein.cshl.org/cgi-bin/perlref?func=redo)
restart a loop from the top


ref (http://stein.cshl.org/cgi-bin/perlref?func=ref)
return the type of a variable reference


rename (http://stein.cshl.org/cgi-bin/perlref?func=rename)
rename or move a file


require (http://stein.cshl.org/cgi-bin/perlref?func=require)
load functions defined in a library file


return (http://stein.cshl.org/cgi-bin/perlref?func=return)
return a value from a user-defined subroutine


reverse (http://stein.cshl.org/cgi-bin/perlref?func=reverse)
reverse a string or list


rewinddir (http://stein.cshl.org/cgi-bin/perlref?func=rewinddir)
rewind a directory handle to the beginning


rindex (http://stein.cshl.org/cgi-bin/perlref?func=rindex)
find a substring in a larger string, from right to left


rmdir (http://stein.cshl.org/cgi-bin/perlref?func=rmdir)
remove a directory


s/// (http://stein.cshl.org/cgi-bin/perlref?func=s///)
pattern substitution operation


scalar (http://stein.cshl.org/cgi-bin/perlref?func=scalar)
force an expression to be treated as a scalar


seek (http://stein.cshl.org/cgi-bin/perlref?func=seek)
reposition a filehandle to an arbitrary point in a file


select (http://stein.cshl.org/cgi-bin/perlref?func=select)
make a filehandle the default for output


shift (http://stein.cshl.org/cgi-bin/perlref?func=shift)
shift a value off the beginning of an array


sin (http://stein.cshl.org/cgi-bin/perlref?func=sin)
sine


sleep (http://stein.cshl.org/cgi-bin/perlref?func=sleep)
put the script to sleep for a while


sort (http://stein.cshl.org/cgi-bin/perlref?func=sort)
sort an array or list by user-specified criteria


splice (http://stein.cshl.org/cgi-bin/perlref?func=splice)
insert/delete array items


split (http://stein.cshl.org/cgi-bin/perlref?func=split)
split a string into pieces according to a pattern


sprintf (http://stein.cshl.org/cgi-bin/perlref?func=sprintf)
formatted string creation


sqrt (http://stein.cshl.org/cgi-bin/perlref?func=sqrt)
square root


stat (http://stein.cshl.org/cgi-bin/perlref?func=stat)
get information about a file


sub (http://stein.cshl.org/cgi-bin/perlref?func=sub)
define a subroutine


substr (http://stein.cshl.org/cgi-bin/perlref?func=substr)
extract a substring from a string


symlink (http://stein.cshl.org/cgi-bin/perlref?func=symlink)
create a symbolic link


system (http://stein.cshl.org/cgi-bin/perlref?func=system)
execute an operating system command, then return to Perl


tell (http://stein.cshl.org/cgi-bin/perlref?func=tell)
return the position of a filehandle within a file


tie (http://stein.cshl.org/cgi-bin/perlref?func=tie)
associate a variable with a database


time (http://stein.cshl.org/cgi-bin/perlref?func=time)
return number of seconds since January 1, 1970


tr/// (http://stein.cshl.org/cgi-bin/perlref?func=tr///)
replace characters in a string


truncate (http://stein.cshl.org/cgi-bin/perlref?func=truncate)
truncate a file (make it smaller)


uc (http://stein.cshl.org/cgi-bin/perlref?func=uc)
uppercase a string


ucfirst (http://stein.cshl.org/cgi-bin/perlref?func=ucfirst)
uppercase first character of a string


umask (http://stein.cshl.org/cgi-bin/perlref?func=umask)
change file creation mask


undef (http://stein.cshl.org/cgi-bin/perlref?func=undef)
undefine (remove) a variable


unlink (http://stein.cshl.org/cgi-bin/perlref?func=unlink)
delete a file


unpack (http://stein.cshl.org/cgi-bin/perlref?func=unpack)
the reverse of pack


untie (http://stein.cshl.org/cgi-bin/perlref?func=untie)
the reverse of tie


unshift (http://stein.cshl.org/cgi-bin/perlref?func=unshift)
move a value onto the beginning of an array


use (http://stein.cshl.org/cgi-bin/perlref?func=use)
import variables and functions from a library module


values (http://stein.cshl.org/cgi-bin/perlref?func=values)
return the values of a hash variable


wantarray (http://stein.cshl.org/cgi-bin/perlref?func=wantarray)
return true in an array context


warn (http://stein.cshl.org/cgi-bin/perlref?func=warn)
print a warning to standard error


write (http://stein.cshl.org/cgi-bin/perlref?func=write)
formatted report generation


Creating Your Own Functions


You can define your own functions or redefine the built-in ones using the sub function. This is described in more detail in a later lecture.

Variables

A variable is a symbolic placeholder for a value, a lot like the variables in algebra. Perl has several built-in variable types:
Scalars: $variable_nameA single-valued variable, always preceded by a $ sign.Arrays: @array_nameA multi-valued variable indexed by integer, preceded by an @ sign.Hashes: %hash_nameA multi-valued variable indexed by string, preceded by a % sign.Filehandle: FILEHANDLE_NAMEA file to read and/or write from. Filehandles have no special prefix, but are usually written in all uppercase.We discuss arrays, hashes and filehandles later.Scalar Variables

Scalar variables have names beginning with $. The name must begin with a letter or underscore, and can contain as many letters, numbers or underscores as you like. These are all valid scalars:




$foo
$The_Big_Bad_Wolf
$R2D2
$_____A23

$Once_Upon_a_Midnight_Dreary_While_I_Pondered_Weak _and_Weary

You assign values to a scalar variable using the = operator (not to be confused with ==, which is numeric comparison). You read from scalar variables by using them wherever a value would go.
A scalar variable can contain strings, floating point numbers, integers, and more esoteric things. You don't have to predeclare scalars. A scalar that once held a string can be reused to hold a number, and vice-versa:


Code:


$p = 'Potato'; # $p now holds the string "potato" $bushels = 3; # $bushels holds the value 3 $potatoes_per_bushel = 80; # $potatoes_per_bushel contains 80; $total_potatoes = $bushels * $potatoes_per_bushel; # 240 print "I have $total_potatoes $p\n";


Output:

I have 240 Potato
Scalar Variable String Interpolation

The example above shows one of the interesting features of double-quoted strings. If you place a scalar variable inside a double quoted string, it will be interpolated into the string. With a single-quoted string, no interpolation occurs.
To prevent interpolation, place a backslash in front of the variable:




print "I have \$total_potatoes \$p\n"; # prints: I have $total_potatoes $p


Operations on Scalar Variables

You can use a scalar in any string or numeric expression like $hypotenuse = sqrt($x**2 + $y**2) or $name = $first_name . ' ' . $last_name. There are also numerous shortcuts that combine an operation with an assignment:


$a++Increment $a by one$a--Decrement $a by one$a += $bModify $a by adding $b to it.$a -= $bModify $a by subtracting $b from it.$a *= $bModify $a by multiplying $b to it.$a /= $bModify $a by dividing it by $b.$a .= $bModify the string in $a by appending $b to it.

Example Code:


$potatoes_per_bushel = 80; # $potatoes_per_bushel contains 80; $p = 'one'; $p .= ' '; # append a space $p .= 'potato'; # append "potato" $bushels = 3; $bushels *= $potatoes_per_bushel; # multiply print "From $p come $bushels.\n";


Output:

From one potato come 240.
Preincrement vs Postincrement

The increment (++) operator can be placed before or after the variable name, and in either case, the effect on the variable is to bump it up by one. However, when you put the operator before the variable name, the value of the expression as a whole is the value of the variable after the operation (preincrement). If you put the operator after the variable name, the value of the expression is the value of the variable before it was incremented:




$potatoes = 80; # $potatoes holds 80 $onions = ++$potatoes; # $onions holds 81, $potatoes holds 81 $parsnips = $potatoes++; # parsnips holds 81, $potatoes holds 82


The decrement (--) operator works the same way.
Weird Perl Assignment Idioms

Modify a Value and Save the Original in One Operation



$potatoes = 80; # $potatoes holds 80 ($onions = $potatoes) += 10; # $onions now 90, and $potatoes still 80 $sequence = 'GAGTCTTTTGGG'; ($reversec = reverse $sequence) =~ tr/GATC/CTAG/; # reverse reverses a string # tr/// translates one set of characters into another # $sequence holds 'GAGTCTTTTGGG' # $reversec holds 'CCCAAAAGACTC'


Swap the Values of Two Variables

Here's a simple way to swap the values of two variables in one fast step:




($onions,$potatoes) = ($potatoes,$onions); # $onions now holds the original value of $potatoes, and vice-versa


NOTE: The obvious alternative DOES NOT work:




$onions = $potatoes; $potatoes = $onions; # oops!


Here a correct non-idiomatic alternative:




$tmp = $onions; $onions = $potatoes; $potatoes = $tmp;


Rotate the Values of Three Variables



($onions,$potatoes,$turnips) = ($potatoes,$turnips,$onions); # $onions <- $potatoes # $potatoes <- $turnips # $turnips <- $onions




Processing Command Line Arguments


When a Perl script is run, its command-line arguments (if any) are stored in an automatic array called @ARGV. You'll learn how to manipulate this array later. For now, just know that you can call the shift function repeatedly from the main part of the script to retrieve the command line arguments one by one.
Printing the Command Line Argument


Code:


#!/usr/bin/perl # file: echo.pl $argument = shift; print "The first argument was $argument.\n";



Output:


(~) 50% chmod +x echo.pl(~) 51% echo.pl tunaThe first argument was tuna.(~) 52% echo.pl tuna fishThe first argument was tuna.(~) 53% echo.pl 'tuna fish'The first argument was tuna fish.(~) 53% echo.plThe first argument was .
Computing the Hypotenuse of a Right Triangle


Code:


#!/usr/bin/perl # file: hypotenuse.pl $x = shift; $y = shift; $x>0 and $y>0 or die "Must provide two positive numbers"; print "Hypotenuse=",sqrt($x**2+$y**2),"\n";



Output:


(~) 82% hypotenuse.plMust provide two positive numbers at hypotenuse.pl line 6.(~) 83% hypotenuse.pl 1Must provide two positive numbers at hypotenuse.pl line 6.(~) 84% hypotenuse.pl 3 4Hypotenuse=5(~) 85% hypotenuse.pl 20 18Hypotenuse=26.9072480941474(~) 86% hypotenuse.pl -20 18Must provide two positive numbers at hypotenuse.pl line 6.



<<----- Perl Basics (http://mmofuse.net/forums/f63/perl-basics-1-a-19913/)2 (http://mmofuse.net/forums/f63/perl-basics-2-a-19914/)
Perl Basics 4 ----->> (http://mmofuse.net/forums/f63/perl-basics-4-a-19916/)