In: Computer Science
while ( my $str = < > )
{
print $str;
}
1) characteristics of hash in Perl and equivalent data type in python?
A) - Hash is simply a set of key or value pairs of elements.
- We use Hash variables here which are preceded by a percent sign (%)
- syntax to refer to a single element of a hash:
$data{key}
Where data = set of key/value pairs
Eg: %data = (‘charan’,1,’vinay’,2);
print “\$data{‘charan’} = $data{‘charan’} \n”;
print “\$data{‘vinay’} = $data{‘vinay’} \n”;
output: $data{‘charan’} = 1
$data{‘vinay} = 2
- Equivalent data type of hash in Perl to python:
Python’s dictionaries work like hashes that are found in Perl
2) Explain < > in the following Perl code?
while (my $str = < >)
{
print $str;
}
A.
- <> is referred as diamond operator in Perl
- It is mainly used as read line operator
- In the above code it is taking input from command line and prints it.
- It will continue taking input and printing it as while loop is not breaking and every time its value is true
3) Can we use different data types for the elements of an array?
A. - Yes, it is only possible when we declare the array as an object
- An item in an array of objects can have a reference to any other object with different type
- e.g.:
use strict;
use warnings;
package Sample;
#constructor
Sub new {
my $class = shift;
my $self = {
‘text’ => shift,
‘number’ =>shift
};
bless $self, $class;
return $self;
}
my $obj = new Sample(“charan”,19); //both are different data types
print “$obj->{‘text’} \n”;
output: charan
4) What is Perl matching in Perl?
A. – Perl matching means matching a pattern for a specified number of occurrences.
- It has special operator to test the particular pattern occurrence in a character string
- And that operator is =~ m
- e.g.: $s = “It is a sample text”;
$s =~ m/is a/;
print “Before s: $`\n”; //everything before the matched s
print “Matched s: $&\n”; // entire matched s
print “After s: $’\n”; // everything after the matched s
output:
Before s: It
Matched s: is a
After s: sample text
5) Explain bless function in Perl
A. Bless:
- it simply associates an object with a class
- if you see this example
package Sample;
#constructor
Sub new {
my $class = shift;
my $self = {
‘text’ => shift,
‘number’ =>shift
};
bless $self, $class;
return $self;
}
my $obj = new Sample(“charan”,19); //both are different data types
print “$obj->{‘text’} \n”;
- This example shows its basic usage
- The object reference is created by blessing a reference to the package’s class
Where reference is $self and class name is $class
Thank you
Kindly vote my answer and feel free to comment if you have any doubts