Perl control structures

Last updated

The basic control structures of Perl are similar to those used in C and Java, but they have been extended in several ways.

Contents

Loops

In the following, label is an optional identifier terminated by a colon, and block is a sequence of one of more Perl statements surrounded by braces. All looping constructs except for the C-style for-loop can have a continue block that is executed after each iteration of the loop body, before the loop condition is evaluated again.

labelfor ( expr1 ; expr2 ; expr3 ) block

This is the so-called C-style for loop. The first expression is evaluated prior to the first loop iteration. The second expression is evaluated prior to each iteration and the loop is terminated if it evaluates to false. The third expression is evaluated after each iteration, prior to deciding whether to perform the next. This for loop is the only looping construct that can not have a continue block, but expr3 is functionally equivalent.

labelforvar ( list ) blocklabelforvar ( list ) blockcontinueblocklabelforeachvar ( list ) blocklabelforeachvar ( list ) blockcontinueblock

In foreach, var is a scalar variable that defaults to $_ if omitted. For each element of list, var is aliased to the element, and the loop body is executed once. The keywords for and foreach are synonyms and are always interchangeable.

labelwhile ( expr ) blocklabelwhile ( expr ) blockcontinueblocklabeluntil ( expr ) blocklabeluntil ( expr ) blockcontinueblock

The while loop repeatedly executes the loop body as long as the controlling expression is true. The condition is evaluated before the loop body. until is similar, but executes the loop body as long as the condition is false.

labelblocklabelblockcontinueblock

The labelblock construct is a bit of an oddity: Perl treats a bare block with or without a label as a loop that is executed once. This means that the loop control keywords can be used to restart the block or to exit it prematurely; a bare block can also have a continue block.

Loop control keywords

Perl provides three loop control keywords that all accept an optional loop label as an argument. If no label is specified, the keywords act on the innermost loop. Within nested loops, the use of labels enables control to move from an inner loop to an outer one, or out of the outer loop altogether. The loop control keywords are treated as expressions in Perl, not as statements like in C or Java.

Conditional statements

if ( expr ) blockif ( expr ) blockelseblockif ( expr ) blockelsif ( expr  ) block ... elseblockunless ( expr ) blockunless ( expr ) blockelseblockunless ( expr ) blockelsif ( expr  ) block ... elseblock

where block is a sequence of one of more Perl statements surrounded by braces.

The controlling expressions are evaluated in a boolean context: The numeric value 0, the strings "" and "0", and the undefined value undef are false, all other values are true. This means that the strings "0.0", "00", "-0", and "0 but true" are all true, even though their value would be converted to 0 in a numeric context; values like these are sometimes used when a successful operation needs to return 0.

Evaluating an empty array in scalar context yields undef, which is false. Therefore, the following example prints "a is empty":

my@a=();'''unless'''(@a){'''print'''"a is empty"}

Statement modifiers

Perl also provides variants of the loop and conditional constructs that work on a simple statement (an expression evaluated for its side-effects) instead of a block:

statementifexpr; statementunlessexpr; statementwhileexpr; statementuntilexpr; statementforlist; statementforeachlist;

The while and until modifiers test the controlling expression before executing the statement, just like their loop counterparts. However, they are not considered actual loops, so the loop control keywords next, last and redo cannot be used with them. They have special semantics when combined with the do keyword:

doblockwhileexpr; doblockuntilexpr;

In these constructs, the condition is tested after the block is executed, so the block always executes at least once.

These modifiers cannot be nested, so the following is illegal

statementifexpressionforlist;         #ERROR

and should be written as one of:

( expression ) and ( statement ) forlist; for ( list ) { statementifexpression } do { statementifexpression } foreachlist;

goto

There are two forms of goto in Perl:

goto label

and

goto &subroutine

The first form is generally deprecated, and is only used in rare situations. For example, when attempting to preserve error status in $?, some modules will use goto like this:

open(A,"<",$filea)orgotofail;open(B,">",$fileb)orgotofail;printB<A>orgotofail;closeAorgotofail;closeBorgotofail;return1;fail:$reason="In copy: $?";return0;

The second form is called a tail call, and is used to enhance the performance of certain kinds of constructs where Perl's default stack management would perform non-optimally. For example:

subfactorial{my$n=shift;my$total=shift(@_)||1;if($n>1){@_=($n-1,$total*$n);goto&factorial;}else{return$total;}}

This form is also used to create aliases for subroutines with minimal overhead. This can help reduce "Out of Memory" errors (or high memory usage in general) found often in repeating the same subroutine.

Wikibooks-logo-en-noslogan.svg Perl Programming/Flow control at Wikibooks

Related Research Articles

Structured programming is a programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making extensive use of the structured control flow constructs of selection (if/then/else) and repetition, block structures, and subroutines.

In computer science, control flow is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an imperative programming language from a declarative programming language.

<span class="mw-page-title-main">Conditional (computer programming)</span> Control flow statement that executes code according to some condition(s)

In computer science, conditionals are programming language commands for handling decisions. Specifically, conditionals perform different computations or actions depending on whether a programmer-defined boolean condition evaluates to true or false. In terms of control flow, the decision is always achieved by selectively altering the control flow based on some condition.

<span class="mw-page-title-main">While loop</span> Control flow statement for repeating execution until a condition is met

In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

<span class="mw-page-title-main">For loop</span> Control flow statement for repeated execution

In computer science a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for loop functions by running a section of code repeatedly until a certain condition has been satisfied.

In computer science, a generator is a routine that can be used to control the iteration behaviour of a loop. All generators are also iterators. A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values. However, instead of building an array containing all the values and returning them all at once, a generator yields the values one at a time, which requires less memory and allows the caller to get started processing the first few values immediately. In short, a generator looks like a function but behaves like an iterator.

<span class="mw-page-title-main">Foreach loop</span> Control flow statement for traversing items in a collection

In computer programming, foreach loop is a control flow statement for traversing items in a collection. foreach is usually used in place of a standard for loop statement. Unlike other for loop constructs, however, foreach loops usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one errors and makes code simpler to read. In object-oriented languages, an iterator, even if implicit, is often used as the means of traversal.

TI-BASIC is the official name of a BASIC-like language built into Texas Instruments (TI)'s graphing calculators. TI-BASIC is a language family of three different and incompatible versions, released on different products:

In computer programming, the ternary conditional operator is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, ternary if, or inline if. An expression a ? b : c evaluates to b if the value of a is true, and otherwise to c. One can read it aloud as "if a then b otherwise c". The form a ? b : c is by far and large the most common, but alternative syntaxes do exist; for example, Raku uses the syntax a ?? b !! c to avoid confusion with the infix operators ? and !, whereas in Visual Basic .NET, it instead takes the form If(a, b, c).

In most computer programming languages a do while loop is a control flow statement that executes a block of code and then either repeats the block or exits the loop depending on a given boolean condition.

In computer programming, a return statement causes execution to leave the current subroutine and resume at the point in the code immediately after the instruction which called the subroutine, known as its return address. The return address is saved by the calling routine, today usually on the process's call stack or in a register. Return statements in many programming languages allow a function to specify a return value to be passed back to the code that called the function.

In computer programming, a statement is a syntactic unit of an imperative programming language that expresses some action to be carried out. A program written in such a language is formed by a sequence of one or more statements. A statement may have internal components.

xHarbour is a free multi-platform extended Clipper compiler, offering multiple graphic terminals (GTs), including console drivers, GUIs, and hybrid console/GUIs. xHarbour is backward-compatible with Clipper and supports many language syntax extensions, greatly extended run-time libraries, and extensive third party support.

In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.

PROMELA is a verification modeling language introduced by Gerard J. Holzmann. The language allows for the dynamic creation of concurrent processes to model, for example, distributed systems. In PROMELA models, communication via message channels can be defined to be synchronous, or asynchronous. PROMELA models can be analyzed with the SPIN model checker, to verify that the modeled system produces the desired behavior. An implementation verified with Isabelle/HOL is also available, as part of the Computer Aided Verification of Automata (CAVA) project. Files written in Promela traditionally have a .pml file extension.

In programming languages, a label is a sequence of characters that identifies a location within source code. In most languages, labels take the form of an identifier, often followed by a punctuation character. In many high-level languages, the purpose of a label is to act as the destination of a GOTO statement. In assembly language, labels can be used anywhere an address can. Also in Pascal and its derived variations. Some languages, such as Fortran and BASIC, support numeric labels. Labels are also used to identify an entry point into a compiled sequence of statements.

The syntax and semantics of PHP, a programming language, form a set of rules that define how a PHP program can be written and interpreted.

<span class="mw-page-title-main">Goto</span> One-way control statement in computer programming

Goto is a statement found in many computer programming languages. It performs a one-way transfer of control to another line of code; in contrast a function call normally returns control. The jumped-to locations are usually identified using labels, though some languages use line numbers. At the machine code level, a goto is a form of branch or jump statement, in some cases combined with a stack adjustment. Many languages support the goto statement, and many do not.

The structure of the Perl programming language encompasses both the syntactical rules of the language and the general ways in which programs are organized. Perl's design philosophy is expressed in the commonly cited motto "there's more than one way to do it". As a multi-paradigm, dynamically typed language, Perl allows a great degree of flexibility in program design. Perl also encourages modularization; this has been attributed to the component-based design structure of its Unix roots, and is responsible for the size of the CPAN archive, a community-maintained repository of more than 100,000 modules.