How to Use Labels in Perl

How to Use Labels in Perl thumbnail
The Perl programming language utilizes a nested structure to help the parser navigate the program.

Perl is a powerful programming language that enables the programmer to take a high degree of control over the program. Labels are used to help Perl programmers organize the program. A label can be applied to a loop or a switch. Loops and switches nested within the labeled loop can then call back to the broader structure without adding a termination exception to every switch and loop along the way. Thus, the programmer can skip around the structure of the code quickly and simply.

Instructions

    • 1

      Create two arrays that require specialized sorting. These arrays will be taken for an example:

      @animals =('Black Cats','Black Dogs','Dairy Cows','Wild Horses',''Monkeys');

      @lucky =('Under Ladder', 'Black Cats','Spilled Salt','13');

    • 2

      Sort through the names with nested loops as follows:

      @animals =('Black Cats','Black Dogs','Dairy Cows','Wild Horses',''Monkeys');

      @lucky =('Under Ladder', 'Black Cats','Spilled Salt','13');

      foreach $creature (@animals) {

      print "$creature\n";

      if ($creature =~/Black /) {

      foreach $charm (@lucky) {

      print "\t$charm\n";

      last if $charm eq $lucky;

      }

      }

      }

      Here we search through the animals array for bad luck charms. The loop charms loop will close when "Black Cats" are encountered in both loops, but the overarching animal loop will continue.

    • 3

      Insert a label to clear up the confusion:

      @animals =('Black Cats','Black Dogs','Dairy Cows','Wild Horses',''Monkeys');

      @lucky =('Under Ladder', 'Black Cats','Spilled Salt','13');

      Label: foreach $creature (@animals) {

      print "$creature\n";

      if ($creature =~/Black /) {

      foreach $charm (@lucky) {

      print "\t$charm\n";

      last Label if $charm eq $lucky;

      }

      }

      }

      Any name can be used in place of "Label." It needs to be followed by a colon when it is first declared. It can then be called anywhere within the loop or switch it controls. At later portions of the program, it can be called with "Start Label."

Related Searches:

References

  • Photo Credit pearl chain image by OMKAR A.V from Fotolia.com

Comments

You May Also Like

Related Ads

Featured