Listado de la etiqueta: PERL


“The loop is used to iterate some statements multiple times. The foreach loop is one of the useful loops of PERL. This loop is mainly used for iterating the array of values that contains the list of data. It can be used for other purposes also, such as reading file content, controlling the iteration using different keywords, etc. Different uses of the foreach loop have been shown in this tutorial.”

Syntax

Different syntaxes of foreach loop are given below.

A. foreach var (array) {
statement(s);
}

The above foreach loop is used to iterate the array values.

B. foreach var (file_handler) {
statement(s);
}

The above foreach loop is used to read the content of a file.

C. foreach var ( ) {
statement(s);
}

The above foreach loop is used to read the user inputs.

Different uses of the foreach loop have been shown in the next part of this tutorial.

Example-1: Read a One-Dimensional Array

Create a PERL file with the following code that will iterate the values of a one-dimensional array using a foreach loop and print each value of the array in a line. An array of 5 string values has been defined in the code. In each iteration of the loop, each value of the array will be parsed and printed in the output with the newline.

# Declare an array of string values
@students = («Mir Sabbir», «Meena Chowdhury», «Mújol Rahman», «Nirob Hossain», «Keya khan»);

# Iterate the array values using the foreach loop
foreach $value (@students)
{
    # Print the array value
    print «$valuen«;
}

Output
The following output will appear after executing the above code.

Example-2: Read a Two-Dimensional Array

Create a PERL file with the following code that will iterate the values of a two-dimensional array using a foreach loop and print each value of the array in a line. A two-dimensional array of 4 rows and 3 columns has been defined in the code. An extra newline has been added after iterating all values of a row. The values of each row have been parsed by using the object variable defined in the loop.

# Declare a two-dimensional array
@students = (
    {
        id => ‘20227856’,
        name => ‘Neha Ali’,
        marks => 89
    },
    {
        id => ‘20224523’,
        name => ‘Mizanur Rahman’,
        marks => 95
    },
    {
        id => ‘20221278’,
        name => ‘Ruhul Amin’,
        marks => 69
    },
    {
        id => ‘20228956’,
        name => ‘Mehrab Hossain’,
        marks => 70
    },
);

# Iterate the array values
foreach $std (@students)
{
    # Print the array values
    print «Student ID:», $std>{‘id’}, «n«;
    print «Student Name:», $std>{‘name’}, «n«;
    print «Student Marks:», $std>{‘marks’}, «nn«;
}

Output
The following output will appear after executing the above code.

Example-3: Read the Range of Values

Create a PERL file with the following code that will iterate the foreach loop based on the values of a range array. In each iteration, a number value will be taken from the user and inserted into an array. The values of this array will be printed after completing the iteration of the loop.

# Declare an array
@lines;
# Iterate the loop 4 times
foreach $numbers (1 .. 4)
{
    # Print message for the user
    print «Enter a number:»;
    # Take input from the user
    $line = ;
    # Add the input value into the array
    push @lines, $line;
}
# Print the array values
print «nArray values are:n«, @lines;

Output
The following output will appear after executing the above code.

Example-4: Read the Content of a File

Create a text named myfile.txt with the following content before testing the code of this example.

myfile.txt

Perl is a general-purpose programming language.

It is similar in syntax to the C language.

It is an open-source and interpreted language.

Create a PERL file with the following code that will read the content of the myfile.txt file and print the file content by using a foreach loop. The open() function has been used in the code to open the file for reading. The “<” symbol is used to open a file for reading in PERL. Next, the foreach loop has been used to read and print the file content line by line.

# Set the filename
$filename = ‘myfile.txt’;
# Open the file for reading
open $file_handler, ‘<‘, $filename or die «Unable to open $filename file.»;

# Read each line of the file using foreach loop
foreach $line () {
    # Print the line of the file
    print $line;
}

Output
The following output will appear after executing the above code if the myfile.txt file does not exist in the current location.

After creating the myfile.txt file, the following output will appear after executing the above script.

Example-5: Control the foreach loop Using the “last” Keyword

Create a PERL file with the following code in which the foreach loop will be terminated by using the last keyword based on the “if” condition. The foreach loop will iterate 10 times based on the range array. The loop will be terminated after iterating the loop 4 times.

# Define the loop to iterate 10 times
foreach $number (1 .. 10) {
    # Print the current value  
    print «The current number is $number.n«;
    #Terminate the loop based on the ‘if’ condition
    last if $number > 3;
}
# Print the termination message
print «The loop is terminated.n«;

Output
The following output will appear after executing the above code.

Example-6: Read the Values of Multiple Arrays

Create a PERL file with the following code that will print the values of two numeric arrays by using a single foreach loop. The values of two arrays and the merged values of these arrays will be printed after executing the code.

# Define the first array
@array1 = (20, 30, 65);
# Define the second array
@array2 = (45, 18, 60, 11);

print «The first array values are:n«, join(‘ ‘,@array1),«n«;
print «The second array values are:n«, join(‘ ‘,@array2),«n«;
print «The values of both arrays are:n«;

# Read the values of both arrays using loop
foreach $number (@array1, @array2)
{
    # Print the array value
    print «$number «;
}
print «n«;

Output
The following output will appear after executing the above code

Conclusion

The ways of using the foreach loop to parse one-dimensional arrays, two-dimensional arrays, multiple arrays, and the file content have been shown in this tutorial to help the PERL user to know the uses of the foreach loop in PERL properly.



Source link


“Sometimes, it requires executing one or more statements based on a particular condition. This problem can be solved by using the “if” statement. It is a very useful statement for any programming language. The ways of using different types of “if” statements in the PERL script have been shown in this tutorial.”

Syntax

Different syntaxes of “if” statements are given below.
A. if statement

If (condition) {
statement(s)
}

The above syntax is used to execute the statements if the condition defined in the “if” statement returns true.

B. if-else statement

If (condition) {
statement(s)
} else{
statement(s)
}

The above syntax is used to execute the statements of the “if” block if the condition returns true otherwise, execute the statements of the “else” block.

C. if-else-if statement

if (condition) {
statement(s)
} else if (condition) {
statement(s)
}
else if (condition){
statement(s)
}

else {
statement(s)
}

The above syntax is used to execute the statements of the first “if” block if the condition returns true otherwise, execute the statements of the next “else if” block if the condition returns true. If the condition of all “if” block returns false, then the statements of the “else” block will be executed.

The uses of different types of “if” statements have been shown in the next part of this tutorial.

Example-1: Use of “if” Statement

Create a PERL file with the following code that will print the current date and time of the system if the input number taken from the user is greater than or equal to 10; otherwise, nothing will be printed. The localtime() function has been used in the code to read the current date and time of the system.

# Take a number input from the user
print «Enter a number:»;
$value = <>;
# Check if the input value is greater than or equal to 10 or not
if($value >= 10){
    # Read the current date and time
    $datetime = localtime();  
    # Print the current date and time value
    print(«Today is $datetimen«);
}

Output
The following output will appear after executing the above code two times with the input values 10 and 5.

Example-2: Use of “if-else” Statement

Create a PERL file with the following code that compares two number values taken from the user and prints a message based on the values. The chomp() function has been used to remove the newlines from the input values. The int() function has been used to convert the input value into the number before comparing the values. The “if-else” statement has been used here to check whether the input numbers are equal or not.

# Take the number inputs from the user
print «Enter the first number:»;
$value1 = <>;
print «Enter the second number:»;
$value2 = <>;

# Remove the newline from each input
chomp($value1);
chomp($value2);

# Check the input values are equal or not
if(int($value1) == int($value2)){
    print «$value1 and $value2 are equal.n«;
}
else
{
    print «$value1 and $value2 are not equal.n«;
}

Output
The following output will appear after executing the above code with the values 7 and 5.

The following output will appear after executing the above code with the values 4 and 4.

Example-3: Use of “if-elsif-else” Statement

Create a PERL file with the following code that will check whether two number values taken from the user are equal or the first number is greater than the second number, or the first number is less than the second number. The chomp() function has been used to remove the newlines from the input values. The int() function has been used to convert the input value into the number before comparing the values. The “if-elsif-else” statement has been used here to do the task mentioned above and print the appropriate message,

# Take the number of inputs from the user
print «Enter the first number:»;
$value1 = <>;
print «Enter the second number:»;
$value2 = <>;
# Remove the newline from each input
chomp($value1);
chomp($value2);
# Check the input values are equal or not
if(int($value1) == int($value2)){
    print «$value1 and $value2 are equal.n«;
}
# Check the first value is less than the second value
elsif(int($value1) < int($value2))
{
    print «$value1 is less than $value2.n«;
}
else
{
    print «$value1 is greater than $value2.n«;
}

Output
The following output will appear after executing the above code with the values 5 and 5.

The following output will appear after executing the above code with the values 9 and 5.

The following output will appear after executing the above code with the values 3 and 6.

Example-4: Use of nested “if” Statement

Create a PERL file with the following code that uses nested “if” conditions to print a message based on the input value taken from the user. According to the code, if the MCQ mark taken from the user is greater than or equal to 70, then the descriptive marks will be taken from the user, and the second “if” condition will be checked. If the descriptive mark is greater than or equal to 50, then “You have passed the exam.” Any other messages will be printed if any of the “if” conditions return false.

# Take the MCQ marks from the user
print «Enter the MCQ marks: «;
$mcq = <STDIN>;
# Check the first condition
if ($mcq >= 70) {
    # Take the descriptive marks from the user
    print «Enter the descriptive marks: «;
    $descriptive = <STDIN>;
    # Check the second condition
    if ($descriptive >= 50) {
        # Print message when both “if”  conditions return true
        print «You have passed the exam.n«;
    }
    else
    {
        # Print message if the second “if”  condition returns false
        print «You have failed the exam.n«;
    }
} else {
    # Print message if the first “if”  condition returns false
    print «You have failed the exam.n«;
}

Output
The following output will appear after executing the above code with the values 75 and 46.

The following output will appear after executing the above code with the values 77 and 58.

The following output will appear after executing the above code with the value 65.

Conclusion

The way of using simple “if,” “if-else,” “if-elsif-else,” and nested “if” statements have been shown in this tutorial by using multiple examples.



Source link


“The array variable is used in any programming language to store multiple data. The PERL array can contain different types of data such as numbers, strings, Boolean, etc. The “@” symbol is used to declare an array in PERL, and the “$” symbol is used to read the value of the particular array index. The command-line argument values are stored in the PERL array named @ARGV. The uses of the PERL array of the numeric index have been shown in this tutorial.”

Create Array

Different ways to create the PERL array have been shown in this part of this tutorial.

A. Create an Array by Initializing Values

The “@” symbol is used to declare a PERL array with values. The array values are separated by a comma with the first brackets in this type of declaration. Different arrays have been created by initializing the values in the following example.

Example

Create a PERL file with the following code that shows the way of declaring different types of arrays in PERL. Here, the first array contains 4 string values, the second array contains 6 number values, and the third array contains 3 strings and 3 number values. The values of three arrays have been printed by using the print operator. The join() function has been used to combine the array values with a comma (,).

#Define first array
@strArray = («book»,«Pen», «Pencil», «Ruler»);
#Define second array
@numArray = (45, 67, 23.89, 12.43, 23, 78);
#Define third array
@mixArray = («book», 45, «Pen», 10, «Pencil», 5);
#Print array values
print «Array1:», join(‘,’, @strArray),«n«, «Array2:», join(‘,’,@numArray),«n«,«Array3:», join(‘,’,@mixArray),«n«;

Output
The following output will appear after executing the above code.

B. Create an Array by Using the “qw” Operator

The “qw” operator is used to create a PERL array from a string value based on the white space. The “@” symbol is used to declare a PERL array like before. Different arrays have been created by using the “qw” operator in the following example.

Example

Create a PERL file with the following code that shows the way of declaring different types of arrays in PERL by using the “qw” operator. Here, the first array contains 4 string values, the second array contains 6 number values, and the third array contains 3 strings and 3 number values. The values of three arrays have been printed by using the print operator. The join() function has been used to combine the array values with a comma (,) shown in the previous example.

#Define first array
@strArray = qwRose Lily Daisy Zinnia;
#Define second array
@numArray = qw5 6 2.89 1.43 3 8;
#Define third array
@mixArray = qwRose 45 Dalia 10 Lily 5;
#Print array values
print «Array1:», join(‘,’, @strArray),«n«, «Array2:», join(‘,’,@numArray),«n«,«Array3:», join(‘,’,@mixArray),«n«;

Output
The following output will appear after executing the above code.

C. Create an Array by Initializing Each Value Separately

Each value of the array can be initialized separately by mentioning the index value or adding a value without whitespace using the “qw” operator. The “$” symbol is used to set each value of the array. Different ways to create an array by adding a single value have been shown in the following example.

Example

Create a PERL file with the following code that shows the way of declaring the value of an array by mentioning the index value. Here, four string values are added by using double quotes, and 2 string values are added by using the “qw” operator. The values of the array have been printed by using the print operator. The join() function has been used to combine the array values with a comma (,) shown in the previous example.

#Define array values using index and ‘qw’ operator
$months[0] = «January»;
$months[1] = «February»;
$months[2] = qw/March/;
$months[3] = qw/April/;
$months[4] = «May»;
$months[5] = «June»;
#Print the array values
print «Array values:n«, join(‘,’, @months),«n«

Output
The following output will appear after executing the above code.

D. Create Sequential Array

The array of sequential values can be created by using the range values. The “@” symbol is used to declare the range array. Different types of range arrays have been mentioned in the following example.

Example

The sequential array values can be initialized by defining the range. Create a PERL file with the following code that will show the way of initializing array values by using numeric range and character range. The values of these arrays have been printed by using the print operator. The join() function has been used to combine the array values with a comma (,) shown in the previous example.

#Declare array of sequantial numbers
@numArray = (10..20);
#Declare array of sequantial characters
@charArray = (A..M);
#Print the array values
print «Number Array:», join(‘,’, @numArray),«n«, «Character Array:», join(‘,’,@charArray),«n«

Output
The following output will appear after executing the above code.

Access Array Values

All array values can be accessed by using the loop, and the particular array value can be accessed by mentioning the index value. The “$” symbol is used to print a particular array value. The following example shows different ways to access array values.

Example

Create a PERL file with the following code that shows the way of accessing array values in different ways. An array of string values has been defined in the code. Next, the 2nd and 3rd elements of the array have been accessed by mentioning the index value. The foreach loop has been used to access all values of the array and print each value in each line.

#Define the first array
@strArray = («book»,«Pen», «Pencil», «Ruler»);
#Print individual value
print «The value of 2nd index: «,$strArray[1],«nThe value of the 3rd index: «, $strArray[2],«n«;
#Print all array values
print «Array values are:n«;
foreach $value (@strArray)
{
    print «$valuen«;
}

Output
The following output will appear after executing the above code.

Conclusion

The way of creating and accessing the PERL array has been shown in this tutorial by using multiple PERL examples. I hope this tutorial will help the PERL users to know the purpose of using the PERL array properly.



Source link


“The length of an array indicates the number of elements of the particular array. Many ways exist in PERL to calculate the array length. When the length of the array is calculated by using the “@” symbol, then it is called an implicit scalar conversion. When the length of the array is calculated by using the scalar keyword, then it is called an explicit scalar conversion. The “#” symbol can also be used to count the length of the array. Different ways of counting the array length and using it in the PERL scripts have been shown in this tutorial.

Different ways of counting the array length have been described in the next part of this tutorial by using examples.”

Example-1: Count the Array Length Using the “@” Symbol

Create a PERL file with the following code that will count the length of an array by using the “@” symbol. An array of 5 string values has been defined in the code. The total number of array values has been stored into a variable named $length that has been printed later.

# Declare an array of strings
@myArr = (‘php’, ‘java’, ‘perl’, ‘bash’, ‘python’);
# Count the array length
$length = @myArr;
# Display the array length
print «The array contains $length elements.n«;

Output

The following output will appear after executing the above code.

Example-2: Count the Array Length Using the Scalar Keyword

Create a PERL file with the following code that will count the length of an array by using the scalar keyword. An array of 6 numbers have been defined in the code. The scalar keyword has been used to count the total number of elements of the array. Next, two values were added to the array and again counted, the total number of elements of the array. The join() function has been used to print the array values with the space.

# Define an array of numbers
@numbers = (6, 5, 3, 1, 2, 8);
# Print the array values
print «Array values are:n«, join(‘ ‘,@numbers), «n«;
# Print the total number of elements of the array
print «Total elements of the array is «, scalar @numbers, «n«;
#Add two new elements
$numbers[@numbers] = 9;
$numbers[@numbers] = 4;
# Print the array values after adding two values into the array
print «Array values after adding two elements are:n«,join(‘ ‘,@numbers), «n«;
# Print the length of the array after insertion
print «Total elements of the array is «, scalar @numbers, «n«;

Output

The following output will appear after executing the above code. The total number of elements of the array after adding two elements is 6+2 = 8.

Example-3: Count the Array Length Using the “#” Symbol

Another way of counting the total number of elements of the array is using the “#” symbol. The last index of the array is counted by using the “#” symbol. So the total array elements can be counted by adding 1 with the last index value. Create a PERL file with the following code that will count the array length by using the “#” symbol. An array of 5 float numbers has been defined in the code. The pop() function has been used to remove 3 elements from the array. The join() function has been used to print the array values with the space.

# Declare an array of float numbers
@float_num = (45.89, 34.12, 56.34, 90.34, 45.23);
# Print the array values
print «Array values:n«, join(‘ ‘,@float_num), «n«;
# Print the length of the array
print «Total number of array elements : «, $#float_num+1, «n«;
# Remove three elements from the array
pop @float_num;
pop @float_num;
pop @float_num;
# Print the array values
print «Array values after removing three elements:n«, join(‘ ‘,@float_num), «n«;
# Print the length of the array after removing three values
print «Total number of array elements after removing the elements: «, $#float_num+1, «n«;

Output

The following output will appear after executing the above code. The total number of elements of the array after removing 3 elements is 5-3 = 2.

Example-4: Print the Array Values Using Array Length

Create a PERL file with the following code that will use the length of the array to iterate the values of the array using for loop and print the array values in each line. The last index value of the array has been used here to count the length of the array.

# Declare an array of strings
@myArr = (‘php’, ‘java’, ‘perl’, ‘bash’, ‘python’);
# Iterate the array values based on the array length
for($i = 0; $i < $#myArr+1; $i++)
{
# Print the array values
print $myArr[$i], «n«;
}

Output

The following output will appear after executing the above code.

Example-5: Count the Array Length Using Loop

Another simple way to count the array length is by using any loop. Create a PERL file with the following code that will count the array length by using the foreach loop. An array of 5 string values has been defined here. A counter variable has been used in the code to count the length of the array by incrementing the counter value by 1 in each iteration of the loop.

# Declare an array of strings
@myArr = (‘php’, ‘java’, ‘perl’, ‘bash’, ‘python’);
# Initialize the counter
$counter = 0;
print «Array values:n«;
# Iterate the array values based on the array length
foreach $val (@myArr)
{
# Print the array values
print $val, «n«;
$counter++;
}

# Print the length of the array
print «nTotal number of array elements : «, $counter, «n«;

Output

The following output will appear after executing the above code.

Conclusion

The way of counting the array values in PERL has been shown in this tutorial by using multiple examples. The PERL user can use any of the ways to find out the array length and use it for solving PERL programming problems.



Source link