Control statements in Perl


Control statements Perl – AyeSir.org


goto statement

goto statement is of 3 types:

  • goto LABEL
  • goto EXPR
  • goto &NAME

goto LABEL will move the cursor directly to the statement labelled with LABEL and will start executing from there.

Example: –

#! /usr/bin/perl -w

open (FH, $file1);

@q = < FH >;

open (OUT, “ > output.txt”);

foreach $i (@q) {

$id=1;

goto LABEL;

}

print OUT “1\t”;

LABEL:

print OUT “0\t”;

}

close FH;

close OUT;

goto EXPR can either evaluate the EXPR to a code reference or a label name.

Example: –

#! /usr/bin/perl -w

$i =5;

$string1 = ” BEG”;

$string2 = “IN”;

do

{

If ( $i == 10 ) {

$i = $i +1;

#use goto EXPR

goto $string1.$string2;

# Here string1 and string2 are using concatenation operator (.) for joining.

}

BEGIN: print “ Value of i = $i \n” ;

}

goto &NAME comes out of current subroutine and sends a call to the named subroutine.



Last Statement

Last statement is used inside a loop to exit the loop immediately

Example:

#! /usr/bin/perl -w

$x = 5;

$y = 1;

while ( $x < 10 ) {

if ( $x == 7)

{

$z = $x + $y;

last;

}

print “value of z : $z \n”;

}




Next Statement

Next statement skips the current iteration of the loop and takes the cursor to the beginning of next iteration of the loop. It is like “CONTINUE” statement in C.

Example:

#! /usr/bin/perl -w

@wwe = ( “rock”, “miz”,”cena”,”edge”,”umaga”);

foreach $wrestler ( @wwe ) {

if ( $wrestler == “miz” ) {

next;

} else {

Print “Wrestler name is : $wrestler\n”;

}

Output:

Wrestler name is : rock

Wrestler name is : cena

Wrestler name is : edge

Wrestler name is : umaga

Redo Statement

The redo statement passes the control to the beginning of the same iteration of the loop without evaluating the condition.

  • redo moves the cursor to the start of the block
  • next moves the cursor to the end of the block
  • last moves the cursor out of the block altogether
  • continue is run at end of the block

Example of redo statement:

#! /usr/bin/perl -w

$i = 0;

while ( $i < 5) {

If ( $i == 3 ) {

$j = $i +1;

redo;

}

print “ value of J : $j \n”;

}