If You Already Know Perl, This is All You Need to Know

Embed Size (px)

Citation preview

  • 8/9/2019 If You Already Know Perl, This is All You Need to Know

    1/14

    If you already know Perl, this is all you need to know:

    Because backslashes have a special meaning within BEGIN_TEXT...END_TEXT blocks,backslashes are not used for their normal Perl meaning. Instead, ~~ (double-tilde):

    Perl PGprint "Hello, $name\n";

    print "Hello, $name~~n";abram$aref = \@array;$href = \%hash;$sref = \$scalar;$aref = ~~@array;

    $href = ~~%hash;$sref = ~~$scalar;

    Perl Syntax OverviewStatementsEach statement in Perl must end on a semicolon. Statements can be spread over several lines.Spacing and indentation is for the most part ignored by Perl and should be used to make the

    program more readable. (See the

  • 8/9/2019 If You Already Know Perl, This is All You Need to Know

    2/14

    scalar variables indexed by integers starting with zero. They have an implied order.

    Hash or associate array variable names start with a % sign (e.g. %hash_variable). Hashes alsocontain a set of scalar variables, but the indices can be any string, and they have no implied order.The hash is stored as key-value pairs.

    ConstantsA number: e.g. 3.1415926 or -543.

    A string: e.g. 'How now brown cow' or "How now brown cow".

    An arrray: e.g. ( 1, 1, 2, 3, 5, 8, 12 ).

    A hash: e.g. ('ssn'=>'123-34-5676', 'name'=>'Jane Doe'). The => symbol is translated into a comma,but using => implicity quotes the word to its left, meaning that (ssn=>'123-34-5676', name=>'JaneDoe') works too.

    abramQuotesUnderstanding how to create strings using quotes is important for writing WeBWorK PG problems.The two important concepts are interpolation of variables and temporarily redefining quote tokens.

    There are two basic types of quoted string constants. Double quoted strings "interpolate" variablesembedded in the string they replace variable names by the contents of the variable. Single quotedstrings do not do this.

    Assuming that the value of $a_variable is 3 we have:

    "Let a = $a_variable" becomes Let a = 3.'Let a = $a_variable' remains Let a = $a_variable.

    A perpetual problem is how to insert a quote inside a quoted string. A standard method is to escapethe quote. Remember that the escape character in PG is ~~, not the backslash \ as in normal Perl.

    'Don~~'t forget to escape single quotes within "single" quotes!'Perl has a more elegant method for handling this. You can temporarily redefine the quote characterusing the command qq for double quotes, or q for single quotes. Any character can be defined as aquote character.

    qq!Any character but the exclamation point can occur in this quoted string!q~The variable $A will not be interpolated in this single quoted string~qq{Parentheses, brackets and braces { must be balanced } when used as quote tokens.}

    More on interpolation and on quoting text blocks can be found in the section on theBEGIN_TEXT...END_TEXT construction.

  • 8/9/2019 If You Already Know Perl, This is All You Need to Know

    3/14

    FunctionsThe function names that are not followed by parentheses must have & in front. (The wordsfunction, subroutine and macro are used intechangeably in this document.)

    The function beginproblem requires no arguments (i.e. no parentheses after it), therefore we canwrite it as &beginproblem or as beginproblem() but not beginproblem which will usually cause a

    compiler warning message about "barewords" appearing in the problem.

    Mathematical operations

    The Perl symbol for taking some value to a power is **. To take variable $a to the power 2, write$a**2, and not $a^2. (When using MathObjects to specify a formula as a string you can use either

    ** or ^. Students can use ^ as well.

    References more complicated data typesReferencesTo handle objects, which are more complicated structures than scalars, lists and hashes we usereferences. A reference is a scalar which is not the object itself, but the address of the object. Forexample $ml = new_match_list() can't really fit an entire matching list object into the scalarvariable $ml, instead it just stores the address of where the object structure is stored. An object is astructure which contains both data and functions (called methods) which operate on that data. Youcan tell that $ml is a reference to an object and not just a number, because the statement ref($ml)will return Match (the type of a matching list object). In general ref($var) will print out the kind of

    object pointed to by a scalar variable, and will print nothing if it is just an ordinary number orstring.

  • 8/9/2019 If You Already Know Perl, This is All You Need to Know

    4/14

    Calling and object's methods$ml->choose(4) tells the match list object $ml to perform its choose method,

    choosabraming 4 arguments. The beautyof objects and methods over standard subroutines is that you don't have to give the choosesubroutine a list of questions and answers to choose from it already 'knows' what questions andanswers it has available and will choose 4 of them. The arrow construction is the same as the periodconstruction in Java. In Java you would write ml.choose(). Java's typography is much neater, butunfortunately the period was already being used for string concatenation by Perl, so we're stuck

    with the arrow construction, which takes up more space.

    Pointers to arrays and hashesYou can use references to arrays and to hashes too if you want:

    ref($ra_foo) prints ARRAY and is a reference to an array variable. You write $ra_foo->[1] to get thesecond item stored in the array.$ra_foo->[1]->[0] can be shortened to $ra_foo->[1][2] to simplify addressing multidimensional

  • 8/9/2019 If You Already Know Perl, This is All You Need to Know

    5/14

    arrays. You can also write ~~@array = ~~@{$ra_foo} which has now stored the array pointed to by$ra_foo in the new array variable [email protected]($rh_foo) prints HASH and is a reference to a hash variable. $rh_foo->{first_name} gets thevalue associated with the key 'first_name'. %hash = %{$rh_foo} stores the referenced hash in thenew hash variable %hash.ref($rf_foo) prints 'CODE' and is a reference to a function or subroutine. The construction

    &{$rf_foo}(34) takes the value 34 and uses it as an argument for the subroutine referenced by$rf_foo.

    Note that the array reference variable started with $ra_, the hash reference variable started with $rh_and the function reference variable started with $rf_. This is a naming convention PG uses, (whichis voluntary, not enforced) which helps keep track of the kind of reference stored in a scalarvariable. The convention is useful for macros, and is probably overkill for most short PG problems.

    See alsoMathObjects

    perlintro a brief introduction and overview of Perlperldsc Perl Data Structures CookbookRetrieved from "http://webwork.maa.org/wiki/Basic_Perl_syntax"Categories: Authors | Needs WorkViewsPage Discussion View source History Personal toolsLog in

    NavigationMain PageIntroduction

    Download WeBWorK

  • 8/9/2019 If You Already Know Perl, This is All You Need to Know

    6/14

    Problem Libraries

    abramForumsDatabasesSite mapRecent changesRandom pageHelpdocumentation for

    StudentsInstructorsAdministratorsAuthorsDevelopersmoreCategoriesUsing WeBWorKAssessmentAccessibilitySearch

    ToolboxWhat links hereRelated changesSpecial pagesPrintable versionPermanent link

    This page was last modified on 12 August 2008, at 20:15. This page has been ac

  • 8/9/2019 If You Already Know Perl, This is All You Need to Know

    7/14

  • 8/9/2019 If You Already Know Perl, This is All You Need to Know

    8/14

    Abram

    abram

  • 8/9/2019 If You Already Know Perl, This is All You Need to Know

    9/14

  • 8/9/2019 If You Already Know Perl, This is All You Need to Know

    10/14

  • 8/9/2019 If You Already Know Perl, This is All You Need to Know

    11/14

  • 8/9/2019 If You Already Know Perl, This is All You Need to Know

    12/14

  • 8/9/2019 If You Already Know Perl, This is All You Need to Know

    13/14

  • 8/9/2019 If You Already Know Perl, This is All You Need to Know

    14/14