Hello & Welcome to our community. Is this your first visit? Register
Follow us on
Follow us on Facebook Follow us on Twitter Watch us on YouTube


MMOCoin

Likes Likes:  0
Results 1 to 1 of 1
  1. #1
    Premium
    G4M3R's Avatar
    Join Date
    Mar 2013
    Location
    LEGEN....wait for it....DARY!
    Posts
    33
    Post Thanks / Like
    Rep Power
    12
    Reputation
    38

    Arrow >>Perl Basics 3<<


    Register to remove this ad
    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 absolute value
    chdir change current directory
    chmod change permissions of file/directory
    chomp remove terminal newline from string variable
    chop remove last character from string variable
    chown change ownership of file/directory
    close close a file handle
    closedir close a directory handle
    cos cosine
    defined test whether variable is defined
    delete delete a key from a hash
    die exit with an error message
    each iterate through keys & values of a hash
    eof test a filehandle for end of file
    eval evaluate a string as a perl expression
    exec quit Perl and execute a system command
    exists test that a hash key exists
    exit exit from the Perl script
    glob expand a directory listing using shell wildcards
    gmtime current time in GMT
    grep filter an array for entries that meet a criterion
    index find location of a substring inside a larger string
    int throw away the fractional part of a floating point number
    join join an array together into a string
    keys return the keys of a hash
    kill send a signal to one or more processes
    last exit enclosing loop
    lc convert string to lowercase
    lcfirst lowercase first character of string
    length find length of string
    local temporarily replace the value of a global variable
    localtime return time in local timezone
    log natural logarithm
    m// pattern match operation
    map perform on operation on each member of array or list
    mkdir make a new directory
    my create a local variable
    next jump to the top of enclosing loop
    open open a file for reading or writing
    opendir open a directory for listing
    pack pack a list into a compact binary representation
    package create a new namespace for a module
    pop pop the last item off the end of an array
    print print to terminal or a file
    printf formatted print to a terminal or file
    push push a value onto the end of an array
    q/STRING/ generalized single-quote operation
    qq/STRING/ generalized double-quote operation
    qx/STRING/ generalized backtick operation
    qw/STRING/ turn a space-delimited string of words into a list
    rand random number generator
    read read binary data from a file
    readdir read the contents of a directory
    readline read a line from a text file
    readlink determine the target of a symbolic link
    redo restart a loop from the top
    ref return the type of a variable reference
    rename rename or move a file
    require load functions defined in a library file
    return return a value from a user-defined subroutine
    reverse reverse a string or list
    rewinddir rewind a directory handle to the beginning
    rindex find a substring in a larger string, from right to left
    rmdir remove a directory
    s/// pattern substitution operation
    scalar force an expression to be treated as a scalar
    seek reposition a filehandle to an arbitrary point in a file
    select make a filehandle the default for output
    shift shift a value off the beginning of an array
    sin sine
    sleep put the script to sleep for a while
    sort sort an array or list by user-specified criteria
    splice insert/delete array items
    split split a string into pieces according to a pattern
    sprintf formatted string creation
    sqrt square root
    stat get information about a file
    sub define a subroutine
    substr extract a substring from a string
    symlink create a symbolic link
    system execute an operating system command, then return to Perl
    tell return the position of a filehandle within a file
    tie associate a variable with a database
    time return number of seconds since January 1, 1970
    tr/// replace characters in a string
    truncate truncate a file (make it smaller)
    uc uppercase a string
    ucfirst uppercase first character of a string
    umask change file creation mask
    undef undefine (remove) a variable
    unlink delete a file
    unpack the reverse of pack
    untie the reverse of tie
    unshift move a value onto the beginning of an array
    use import variables and functions from a library module
    values return the values of a hash variable
    wantarray return true in an array context
    warn print a warning to standard error
    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.





    › See More: >>Perl Basics 3<<
    Last edited by G4M3R; 23-03-13 at 06:41 PM.



  2. Related Threads - Scroll Down after related threads if you are only interested to view replies for above post/thread

 

 

Visitors found this page by searching for:

Nobody landed on this page from a search engine, yet!
SEO Blog

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
All times are GMT -5. The time now is 04:43 PM.
Powered by vBulletin® Copyright ©2000-2024, Jelsoft Enterprises Ltd.
See More links by ForumSetup.net. Feedback Buttons provided by Advanced Post Thanks / Like (Lite) - vBulletin Mods & Addons Copyright © 2024 DragonByte Technologies Ltd.
vBulletin Licensed to: MMOPro.org