Last Updated:

Lable Block in C#

Note that complex sentences are described in termes of blocks, not sentences, as in C. Therefore, it is necessary to use parentheses to denote the block.

if (EXPR) BLOCK - An EXPR Boolean expression is evaluated and if true the block is executed.

$var =1;

if ($var == 1)

{ print $var,"\n";

}

Result: 1

if (EXPR) BLOCK else BLOCK2 - If EXPR=true BLOCK is executed otherwise BLOCK2.

$var =2;

if ($var == 1)

{ print "\$var = 1\n";

}

else

{ print "\$var is not equal to 1\n";

}

Result: $var is not equal to 1

if (EXPR1) BLOCK1 elsif (EXPR2) BLOCK2 ... else BLOCK - If EXPR1=true is executed by BLOCK1 otherwise if EXPR2=true is executed by BLOCK2 otherwise ... otherwise BLOCK.

$var = 1;

if ($var == 0)

{ print "\$var = 0\n";

}

elsif ($var == 1)

{ print "\$var = 1\n";

}

else

{ print "Unknown \$var\n";

}

Result: $var = 1

The While loop. Executes BLOCK as long as EXPR = true. The LABEL label is optional and consists of an identifier ending with the ':' character. The label is necessary when using the next, last, and redo control statements inside the cycle block. If there is no label, these statements refer to the beginning of the next cycle. The block after continue is always executed before the Boolean EXPR expression is evaluated. This is similar to EXPR3 in the for clause, so it is convenient to change the loop counters and flags in this block, even if you use the next operator.

Loop control operators. next - similar to continue in C. Goes to the beginning of the current cycle, i.e. repeats the iteration.

M1:

while ($i < 6)

{

++$i; # Increase the counter by 1

next M1 if $i < 3; # Go to the top if $i < 3

++$i; # otherwise increase the counter again by 1

}

continue

{

print "$i "; # Result: 1 2 4 6

}

last - similar to the break operator in C. Immediately interrupts the loop. The continue block is skipped.

M1:

while ($i < 6)

{

++$i; # Increase the counter by 1

last M1 if $i > 3; # Exit loop if $i > 3

++$i; # otherwise increase the counter again by 1

}

continue {

print "$i "; # Score: 2 4

}

redo - start a new loop without computing EXPR and without executing the continue block.

M1:

while ($i < 6)

{

++$i; # Increase the counter by 1

redo M1 if $i == 3; # Next skip for $i = 3

++$i; # otherwise increase the counter again by 1

}

continue {

print "$i "; # Result: 2 5 7

}

Cycle for. LABEL for (EXPR1; EXPR2; EXPR3) BLOCK. The for statement is completely similar to the for operator in C. BEFORE the loop starts, EXPR1 is executed if expr2 = true a block is executed, then EXPR3 is executed.

for ($i = 2; $i < 5; ++$i){

print $i, " "; # Score: 2 3 4

}

print "\nAfter a loop i = $i\n"; # After cycle i = 5

The foreach loop. LABEL foreach VAR (LIST) BLOCK. The VAR variable is assigned in turn to each item in the LIST list and the block is executed. If VAR is omitted, the items are assigned to the built-in variable $_. If you change the VAR value in the body of the block, this will cause a change in the list items because VAR actually points to the current list item. Instead of the word foreach, you can write simply for - these are synonymous words.

@month = ("January", "February", "March"); # Created an array

foreach $i (@month)

{ print $i," "; # Result: January February March

}

foreach $i (@month)

{ $i = uc($i); # Converted to uppercase

}

print@month; # Result: JANUARYFEBRUARYMART

for $i(3,5,7)

{print "$i"; # Result: 3 5 7

}

Blocks and the switch statement. 

A block, regardless of whether it has a label or not, is semantically a loop that is executed once. Therefore, the effect of the next, last, redo loop operators is similar to that described above. Blocks are convenient for building switch structures. In Perl, there is no special switch operator similar to the C language, so you can create the constructions that are convenient for you. The author's experience shows that for simplicity of writing, the if ... elsif ... else ... although you can compose something similar:

SWITCH:

{

if ($i ==1 ) { .....; last SWITCH; }

if ($i ==2 ) { .....; last SWITCH; }

if ($i ==3 ) { .....; last SWITCH; }

$default = 13;

}

Choose to your liking.

The goto operator.

 In Perl, there is a goto operator. When creating large production tasks at the last stage, especially when working out erroneous situations, of course goto is needed.

Perl implements three forms of goto. goto - label, goto - expression and goto - subroutine.

goto label - performs a direct transition to the specified label.

goto - expression - Calculates the name of the label and makes the appropriate transition. For example, if we want to switch to one of the three labels "M1:", "M2:" or "M3:" depending on the values of the variable $i equal to 0, 1 or 2, then it is better to do it as follows:

goto ("M1", "M2", "M3")[$i];

here $i is used as the array index specified directly in the expression.

Goto subroutine is a rather rare case because it is always easier and more reliable to call a subroutine "naturally".

POD operators Documenting programs. Perl implements a very convenient mechanism for writing documentation at the time of creating a program. For this purpose, special POD operators are used. If in the body of the program the interpreter encounters an operator beginning with the symbol '=' for example:

= head Set of standard procedures

then it skips everything down to the word '=cut'. This is useful for including multi-line long or pages of comments. Then, using a special pod program, you can separate the documentation text from the program text.

Variables.

There are three types of data structures in Perl: scalars, scalar arrays, and hashes, associative arrays of scalars. Typically, the elements of arrays are indexed in integers, the first element is zero. A negative index value indicates the item's position number from the end. Hashes are indexed by strings of characters.

Scalar names always begin with the '$' character - even when denoting an array element:

$var 1 # Simple scalar 'var1'

$var 1[0] # The first element of the 'var1' array

$var 1{'first'} # Element with index 'first'

If you use the array name "whole" or its "slice", the array name is preceded by the '@' character:

@var1 #All elements of the var1 array ($var 1[0],$var 1[1],..., $var 1[n])

@var1[1,3,10] # Elements $var 1[1], $var 1[3], $var 1[10]

@var1{'first','last'} #then same as ($var 1{'first'}, $var 1{'last'})

The "whole" hash begins with the '%' character:

%var, %key, %years

The names of the subroutines begin with the '&' character unless it is clear from the context that it is a subroutine:

&sub1, &test_prog, test(12)

Character table names always begin with a '*' character.

Each type of variable has its own memory area so $var 1 and $var 1[0] are completely different variables, although $var 1[0] part of the array @var1. Also @var1 and %var1 are different arrays of variables.

Variable names can contain any alphanumeric characters except spaces and tabs. These characters are used as delimiters. Large and small letters are distinguished because $var 1 and $Var 1 are different variables. In Perl, by default, the names of file labels and pointers are written in large letters.

Context. 

Of great importance for the correct use of built-in functions is the context of using the result of these functions, because otherwise they return a completely "incomprehensible" result. There are two main contexts in Perl: scalar and list. If you mean a single value on the left side of an expression, it's a scalar context. If the set of values is the list:

$var1 = <>; # Read one line of file

@var1 = <>; # Read all file strings into an array @var1

$var1 = (1,2,3); # $var = 3 - number of elements

@var1 = (1,2,3); # Create an array of @var1 with 1,2,3 elements

Scalar values. 

All data in Perl is scalars, scalar arrays, and scalar hashes. Scalar variables can contain numbers, strings, and references. Conversion of the number - string occurs automatically by default. A scalar can have only one single value, although it can be a reference to an array of scalars. Since Perl itself converts numbers into strings and vice versa, the programmer does not need to think about what the function returns.

In Perl, there are no "string" or "number" or "file" types or anything else. It is a context-sensitive polymorphic language for working with texts. The scalar has a Boolean value of TRUE unless it is a zero string or a number of 0.

There are two types of null scalars in Perl, defined and undefined. An undefined value is returned when something does not exist. For example, an unknown variable, the end of a file, or an error. With the defined() function, you can detect this state in advance.

The number of elements in an array is also a scalar and begins with $# characters. In fact, $#var1 is the index of the last element in the array. It must be remembered that the first element has an index of 0, so the number of elements is defined as $#var1 + 1 . Assigning a value to $#var1 will change the length of the array and destroy the "abandoned" values. Assigning a value to an array element with an index greater than $#var1 will increase the size of the array, and assigning it a zero list will reset it.

In a scalar context, the array name returns its length (the last element is returned for the list):

@var1 = (4, 3, 2, 1);# Assign value to array elements

$i = @var1; # Using the scalar context

print $i; # Print result 4 - number of elements

print @var1; # List context, print all items.

To force a scalar value, it is convenient to use the scalar() function:

print scalar(@var1);# Output the length of an array instead of its values

The hash in the scalar context returns "true" if there is at least one key-value pair. In fact, a string of type 2/8 is returned, where 8 is the number of allocated memory "cells" and 2 is the number of used ones.

Scalar constructors. 

Numbers are written in a standard way:

123.123

0.12

.12E-10

0xABCD # Hexadecimal entry

0377 # If 0 at the beginning is octal

123_456_123 # This is also possible for ease of reading.

Strings are limited to single (') or double (") quotation marks:

'Be equal, humble!' or 'Let us build up and be saved.'

You can omit quotation marks in the hash if the index does not contain spaces:

$var 1{first} is the same as $var 1{'first'}

Note that the first single quotation mark must be preceded by a space, otherwise the string will be treated as the name of the variable, because the names allow the use of single quotation marks. Do not use reserved literals in quotation marks __LINE__ (the number of the current line of the program), __FILE__ (the current file). To indicate the end of the program, you can use the literal __END__. All subsequent text is ignored, but it can be read using the data file pointer.

Words in the program that cannot be interpreted at all are treated as strings in quotation marks, so it is recommended that the names of labels and file pointers be written in large letters to avoid a possible "conflict" with reserved words.

In Perl, it is possible to insert the text of a document directly into the program using the "here-doc" (here text) method. It is indicated by the symbols << followed by the limiter word:

print <<EOF; # All lines before EOF are text to be printed.

Hey three of you, come both here!

What are you worth! I'm telling you!!

Colonel Savonkin.

EOF

List builders. 

List - A set of values listed separated by commas and enclosed in parentheses. In a list context, the list returns the last item in the list:

@var1 = (1, 2, 'hello', 1.2); # Assign value to elements.where

$var1[0] = 1,

$var1[1] = 2,

$var 1[2] = 'hello'

$var1[3] = 1.2

$var 1 = (1, 2, 'hello', 1.2);

and here $var 1 = 1.2 i.e. the last value of the list.

It is allowed to use other lists in the list, but in the resulting list it is no longer possible to distinguish between the beginning and the end of the included lists:

@s1 = (1, 2, 3); # First list

@s2 = (6, 7, 8); # Second

@s = (0, @s1, 4, 5, @s2, 9, 10); # Include @s1 and @s2 lists

print @s; # Result: 012345678910 - values without spaces.

A list without items is denoted as () and is called a null list. You can use a list expression as an array name, but take it in parentheses:

print ('January', 'February', 'March')[1];

Result: February

A list can be assigned to a list only if each item in the list on the left side of the expression is valid by type list on the right:

($a, $b, $c) = (1, 2, 3); # $a = 1, $b

Built-in Perl variables.

The following variables have special values in Perl. They are denoted somewhat unusually for the "eye" of programmers, because they usually consist of only two characters, and the first is the "$" symbol, with which the names of all variables begin, and an arbitrary often non-alphanumeric character. If you want to use their "normal" letter synonyms, then you need to specify at the beginning of the program.

The following are the names of the built-in variables in both short and long (verbal) forms. Some of them have read-only access, so you can't change their value.

$_ ($ARG) - Variable - Default for input and search operators. That is, if no variable is specified as an argument, then this one is used.

$digit - contains the substring found in the last search when the template contains metacharacters in parentheses. A digit is the number of parentheses. The first substring is number 1.

$& ($MATCH) - found substring in the last template search.

$` - A substring that precedes the substring found.

$' ($POSTMATCH) is the substring that follows the found substring.

$+ ($LAST_PAREN_MATCH) - substring found in the search with a choice of "or".

$* ($MULTILINE_MATCHING) - if its value is set to 1, then the variable in which the search is carried out will be considered multiline, i.e. containing the characters '\n' - line feed. If the value is 0, the variable is considered a single-line variable.

$. ($INPUT_LINE_NUMBER), ($NR) - the number of the read line of the last input operator. Closing the file causes the value of this variable to be cleared.

$/ ($RS), ($INPUT_RECORD_SEPARATOR) - character - a sign of the end of the input string. The default is '\n'

$| ($OUTPUT_AUTOFLUSH) - If you set this variable to a non-zero value, the output buffer will be reset after each output operation. The default value is 0

$, ($OFS), ($OUTPUT_FIELD_SEPARATOR) - a character added by the print operator after each element from the parameter list.

$\ ($ORS), ($OUTPUT_RECORD_SEPARATOR) - the character added by print after all parameters are displayed.

$" ($LIST_SEPARATOR) - similar to "$,", but is added after each element of the array specified in "....".

$# ($OFMT) is the default format for outputting numbers.

$% ($FORMAT_PAGE_NUMBER) is the default format for displaying page numbers.

$= ($FORMAT_LINES_PER_PAGE) - length of one page. The default is 60 lines.

$- ($FORMAT_LINES_LEFT) - the number of remaining lines on the page.

$~ ($FORMAT_NAME) is the format name of the current output. By default, the name of the pointer.

$^ ($FORMAT_TOP_NAME) is the name of the current format for the page title.

$: ($FORMAT_LINE_BREAK_CHARACTERS) - line breaks for multiline fields. In the format string, such fields begin with '^'. The default is '\n-'.

$^L ($FORMAT_FORMFEED) - format (sheet) translation character. The default is '\f'.

$^A ($ACCUMULATOR) - the current battery value of the write() function for format(). The value of this variable can only be seen when using the formline() function, because write() clears it after each output.

$? ($CHILD_ERROR) - This variable contains the completion status of such processes as: closing pipe, terminating the system(), wait() and '...' functions.

$! ($ERRNO $OS_ERROR) - in numerical context returns the error code errno. In the string - the line of the error message. You can force an error code to assign an error code to this variable to get a system message for this code, or you can set a completion code for the die() function.

$@ ($EVAL_ERROR) - error message of the last eval() command.

$$ ($PID), ($PROCESS_ID) - the number of the current process.

$O ($PROGRAM_NAME) is the name of the program file.

$[ is the number of the first element of an array or string character. The default value is 0.

$] ($PERL_VERSION) - perl version message string. Printed by the command perl -v In a numerical context, this is the version number plus the modification number / 1000.

$^T ($BASETIME) - Time in seconds from the beginning of 1970 when the current program started.

$^X ($EXECUTABLE_NAME) - Perl startup command. Similarly argv[0] in C.

$ARGV is the name of the current file readable by the '<>' operator.

@ARGV is an array of program startup string parameters. Attention! @#ARGV - 1 fewer parameters, because $ARGV[0] is the first parameter (not the program name).

@INC is a list of disk directories that Perl scans to execute do, require, or use commands.

%INC - This hash contains directory names for the names of the files used by the do or require commands. The key is the name of the file and the value is the directory.

$ENV{expression} - the hash %ENV contains the values of the environment variables. Changing these values causes a change in the environment for descendant processes.

$SIG{expression} - the hash %SIG contains the names of subroutines for such system signals as INT, QUIT, PIPE, ... The 'DEFAULT' value is for system processing. 'IGNORE' - ignore this signal.

Regular expressions (templates).

Regular expressions in Perl are most often used in search and replace operators such as s/m/, copula operators =~ or != etc. All these operators have similar options:

i- Do not distinguish between lowercase and uppercase letters.
m- Consider the string to be multiline.
s- One-line string.
x- extended syntax (use of spaces and comments)

These options, denoted as '/x', can be used inside templates using the construct (?...). The templates use the following metacharacters (characters denoting groups of other characters):

\- Consider the next metacharacter as a normal symbol.
^- line beginning
.- One arbitrary character. Except for '\n' - the end of the line.
$- End of line
|- Alternative(s)
()- Grouping
[]- character class

Metacharacters have modifiers (written after the metacharacter):

*- repeated 0 or more times
+- -//- 1 or more times
?- 1 or 0 times
{n}- exactly n times
{n,}- at least once
{n,m}- not less than n, but not more than m

In all other cases, braces are considered normal (regular) characters. Thus, '*' is equivalent to {0,} , '+' - {1,} and '?' - {0,1}. n and m cannot be greater than 65536.

By default, the action of metacharacters is greedy. The match propagates as many times as possible without regard to the result of the following metacharacters. If you want to "reduce their appetite", then use the '?' symbol. This does not change the value of the metacharacters, it just reduces the propagation. Thus:

*?- will become 0 or more
+?- 1 and more
??- 0 or 1 time
{n}?- exactly n times
{n,}?- not less than n times
{n,m}?- greater than or equal to n and less than m times

Templates work in the same way as double quotation marks, so you can use '\' characters (backlash characters) in them:

\t- tab character
\n- new line
\r- Carriage translation
\a- format translation
\v- Vertical tabulation
\a- call
\e- escape
\033- Octal symbol notation
\x1A- Hexadecimal
\c[- Control symbol
\l- lowercase of the next character
\u- upper case -//-
\L- all characters in lowercase up to \E
\U- in the top -//-
\E- Register change limiter
\Q- Undo an action as a metacharacter

Additionally, the following metacharacters have been added to Perl:

\w- Alphanumeric or '_' character
\W- not -//-
\s- One space
\S- One not space
\d- one digit
\D- One is not a number

Note that this is all a "single" character. Use modifiers to indicate the sequence. So:

\w+- Word
\d+- Integer
[+-]?\d+- whole with sign
[+-]?\d+\.? \d*is a number with a period

There are imaginary metacharacters denoting places of change of meaning:

\b- Word boundary
\B- not a word boundary
\A- line beginning
\Z- End of line
\G- end of action m//g

A word boundary (\b) is an imaginary dot between the characters \w and \W. Inside the character class, '\b' denotes the backspace symbol. The metacharacters \A and \Z are similar to '^' and '$', but if the beginning of the string '^' and the end of the string '$' are valid for each line in the multiline string, then \A and \Z denote the beginning and end of the entire multiline string.

If a grouping (parentheses) is used inside the template, the group substring number is denoted as '\digit'. Notice that behind the pattern within an expression or block, these groups are denoted as '$digit'. There are additional variables:

$+- denotes the last match
$&- all coincidence
$`- all until coincidence
$'- all after the match

Code Listing 5.1. Coincidence variables.

$s = "one 1 two 2 and three 3";

if ($s =~ /(\d+)\D+(\d+)/) {

print "$1\n"; # result '1'

print "$2\n"; # '2'

print "$+\n"; # '2'

print "$&\n"; # '1 two 2'

print "$`\n"; # 'One'

print "$'\n"; # 'and three 3'

}

Perl version 5 contains additional template constructs:

(?#комментарий)- Comment in the body of the template.
(?:template)- grouping like '( )', but without backlink
(?=template)- "Looking ahead". For example, /\w+(?=\t)/ corresponds to a word followed by a tab, but the '\t' character is not included in the result.
(?! template)- "looking ahead" on negation.

Code Listing 5.2. Template designs.

$s = "1+2-3*4";

if ($s =~ /(\d)(?=-)/) # Find the number behind which is '-'

{ print "$1\n"; # Result '2'

}

else { print "search error\n";}

$s = "1+2-3*4";

if ($s =~ /(\d)(?! \+)/) # Find a figure for which there is no '+'

{ print "$1\n"; # Result '2'

}

else { print "search error\n";}

Regular expression rules. (regex)

1. Any symbol denotes itself, unless it is a metacharacter. If you need to undo the action of the metacharacter, then put a '\' in front of it.

2. A string of characters denotes a string of these characters.

3. The set of possible characters (class) is enclosed in square brackets '[]', which means that one of the characters indicated in parentheses can be in this place. If the first character in parentheses is '^' - then none of the specified characters can stand in this place of the expression. Within a class, you can use the '-' character to indicate a range of characters. For example, a-z is one of the small letters of the Latin alphabet, 0-9 is a number.

4. All characters, including special ones, can be denoted by '\' as in the C language.

5. Alternate sequences are separated by the '|' character Notice that inside the square brackets this is a regular character.

6. Inside the regular expression, you can specify "sub-templates" enclosing them in parentheses and refer to them as '\number' The first bracket is denoted as '\1'.

Operators and priorities.

In Perl, the associativity and priority of operators is similar to the C language.

Assoc.Operators
lefttermes and left-handed list operators
left->
-++ --
right**
right! ~ \ unary + and -
left=~ !~
left* / % x
left+ - .
left<< >>
-named unary operators
-< > <= >= lt gt le ge
-== != <=> eq ne cmp
left&
left| ^
left&&
left||
-..
right?:
right= += -= *= etc.
left, =>
-right-handed list operators
leftnot
leftand
leftor xor

 

Termes and left-handed list operators. 

Any term has the highest priority. The term includes variables, quotation marks and their operators, arithmetic and logical expressions in parentheses, any functions with parameters in parentheses. In fact, there are no such functions, since these are just unary and list operators. It's just that they behave like functions with parameters in parentheses. If any list statement (print(), etc.) or unary operator (chdir(), etc.) is followed by a left parenthesis, the operators inside the parentheses have the highest priority. As well as the usual functions.

If there are no parentheses, the priority of the list operators is either highest or lowest with respect to the operators to the right or left of it:

@i = ('a','b', print 'c', 'd');

print "\n",@i,"\n"; #Result: c d and a b 1

Here we have the print list operator. For commas to the left of it, it has the lowest priority, but increases the priority with the right comma. Therefore, the right comma is treated as a parameter for print and is printed 'c d', and the left one simply writes the completion code to the array @i and the last print shows this.

The '->' operator C is an infix redirect operator. If there is an [...] or {...} expression to the right of it, then the right part can be a direct or symbolic reference to an array or hash. Otherwise, the right side is a method or a simple scalar containing the name of the method, and the right side is either an object or a class name.

The operators ++ (increment) and -- (decrement). 

They work as in C. If the operator is before the variable, then the value of the variable changes to 1 and the resulting value is used. If after - then its value changes after application. The use of an increment to string variables in Perl has a peculiarity. Each character remains in its class (large, small, digits) and the carrying of the previous character is taken into account. Thus, string variables with numbers work as numeric variables:

print ++($i = "09"); # Result "10"

print ++($i = "a9"); # "b0"

print ++($i = "az"); # "ba"

print ++($i = "aZ"); # "ba"

Operator ** (exponentiation):

print 4**2 # Output 16

print -4**2 # Result -16 i.e. -(4**2)