Perl¶
45 cards — 🟢 8 easy | 🟡 15 medium | 🔴 8 hard
🟢 Easy (8)¶
1. What is a Perl package? And a module?
Show answer
With a Perl package we are defining a namespace.A Perl module in one simple word can be defined as a `class`. When we create a `class` in Perl we use the `package` keyword. A module can be used with the `use` keyword.
2. What is the purpose of the bless function?
Show answer
The function os the `bless` function is used to turning a plain data structure into an object.Example: perl -ne 'print if /ERROR/' access.log — prints lines containing ERROR. The -n flag wraps the code in a while(<>){...} loop.
Remember: "perl -ne = line-by-line filter, perl -pe = line-by-line transform."
3. What is Perl and what are its common use cases in system administration?
Show answer
From the official [docs](https://perldoc.perl.org/):"Perl officially stands for Practical Extraction and Report Language, except when it doesn't."
It's a general purpose programming language developed for manipulating texts mainly. It has been used to perform system administration tasks, networking, building websites and more.
4. What is Perl Open3?
Show answer
From the official [IPC::Open3 docs](https://perldoc.perl.org/IPC::Open3):"IPC::Open3 - open a process for reading, writing, and error handling using open3()".
With `open3` we can have the full control of the STDIN, STDOUT, STDERR. It's usually used to execute commands.
5. What is the difference between .pl and .pm extensions?
Show answer
There's no a real difference between a `.pm` and `.pl` extensions. Perl use `.pm` extensions just to difference it as a perl module (a class). `.pl` extensions are usually named for perl scripts without OOP classes.6. What is a Perl subroutine? How to define it?
Show answer
It's the perl model for user defined functions (this is also called function like other programming languages). We can define a subroutine with the keyword `sub`.```\nsub hello {\n print "hello";\n}\n```
7. What is Perl POD? Can you code an example?
Show answer
From the official [docs](https://perldoc.perl.org/perlpod):"Pod is a simple-to-use markup language used for writing documentation for Perl, Perl programs, and Perl modules."
```\n=item\n This function returns the factorial of a number.\n Input: $n (number you wanna calculate).\n Output: number factorial.\n=cut\nsub factorial {\n my ($i, $result, $n) = (1, 1, shift);\n $result = $result *= $i && $i++ while $i <= $n;\n return $result;\n}\n```
8. What is cpan? And cpanm?
Show answer
CPAN is the Comprehensive Perl Archive Network.CPANM From the official [App::cpanminus](https://metacpan.org/pod/App::cpanminus):
"App::cpanminus - get, unpack, build and install modules from CPAN".
[Find CPAN modules](https://metacpan.org/)
Example: my %ages = ("alice" => 30, "bob" => 25); print $ages{"alice"}; # 30. Use keys %hash to iterate.
Remember: "% = hash (think percent = pairs of things)."
🟡 Medium (15)¶
1. How can you call a method of an inherited class?
Show answer
```\n# Class `A` with `printA` method.\npackage A;\n\nsub new { return bless {}, shift; };\nsub printA { print "A"; };\n\n# Class `B` that extends or use the parent class `A`.\npackage B;\n\nuse parent -norequire, 'A';\n\nsub new { return bless {}, shift; };\n\n# Instance class `B` allows call the inherited method\nmy $b = B->new();\n$b->printA();\n```2. How can you install cpanm and a Perl module?
Show answer
There are some different alternatives to install Perl modules. We will use `cpanm`.- Install `cpanm`:
```\n$ cpan App::cpanminus\n```
- Install the `Test` module with `cpanm`:
```\ncpanm Test\n```
Now we can test the `Test` installed module:
```\n$ perl -M'Test::Simple tests => 1' -e 'ok( 1 + 1 == 2 );'\n1..1\nok 1\n```
```\n$ perl -M'Test::Simple tests => 1' -e 'ok( 1 + 1 == 3 );'\n1..1\nnot ok 1\n# Failed test at -e line 1.\n# Looks like you failed 1 test of 1.\n```
3. How can we evaluate and capture an exception in Perl?
Show answer
From the official [eval docs](https://perldoc.perl.org/functions/eval):"`eval` in all its forms is used to execute a little Perl program, trapping any errors encountered so they don't crash the calling program.".
e.g:
```\neval {\n die;\n};\nif ($@) {\n print "Error. Details: $@";\n}\n```
If we execute this we get the next output:
```\nError. Details: Died at eval.pl line 2.\n```
The `eval` (`try` in another programming languages) is trying to execute a code.
4. Extract all the elements that are numbers in an array
Show answer
```\nmy @array = ('a', 1, 'b', 2, 'c', 3);\nmy @numbers = grep (/\d/, @array); # Note: \d involves more digits than 0-9\nmap {print $_ . "\n" } @numbers;\n```Remember: In regex, $1 is the first capture group. Example: if ($line =~ /user=(\w+)/) { print $1; }
5. Check if the word electroencefalografista exists in a string
Show answer
```\nmy $string = "The longest accepted word by RAE is: electroencefalografista";\nif ($string =~ /electroencefalografista/) { \n print "Match!";\n}\n```Example: use strict; use warnings; catches undeclared variables and common mistakes. Always start scripts with these two lines.
Gotcha: Without strict, Perl silently creates global variables on first use — leading to typo-induced bugs.
6. Check if the word electroencefalografista does not exists in a string
Show answer
```\nmy $string = "The longest not accepted word by RAE is: Ciclopentanoperhidrofenantreno";\nif ($string !~ /electroencefalografista/) {\n print "Does not match!";\n}\n```Example: my $count = 0; declares a lexically scoped variable. my @items = (1,2,3); for arrays, my %map = (a => 1); for hashes.
Remember: "my = mine (local scope), our = shared (package scope)."
7. How can you access to a hash value, add and delete a key/value pair and modify a hash?
Show answer
```\nmy %numbers = (\n 'First' => '1',\n 'Second' => '2',\n 'Third' => '3'\n);\n```- Access:
```\nprint($numbers{'First'});\n```
- Add:
```\n$numbers{'Fourth'} = 4;\n```
- Delete:
```\ndelete $numbers{'Third'};\n```
- Modify:
```\n$numbers{'Fifth'} = 6;\n$numbers{'Fifth'} = 5;\n```
Example: @colors = ("red", "green", "blue"); print $colors[0]; # "red". Use push/pop for stack ops, shift/unshift for queue ops.
Remember: "@ = array (think 'at' multiple items), $ = scalar (single)."
8. Why a Perl class (or module) should return something at the end of the file? Check the example.
Show answer
If we want to `use` a Perl module (`import` a class), this module should end in a value different than 0. This is necessary because if we try to import the class and it has a false value, we will not be able to use it.```\npackage A;\n\nsub new { return bless {}, shift; };\nsub printMethod { print "A\n"; };\n\n1;\n```
9. How to write into a file?
Show answer
```\n# We can use:\n# '>' Write (it clears a previous content if exists).\n# '>>' Append.\nopen(my $fh, '>>', 'file_name.ext') or die "Error: file can't be opened";\nprint $fh "writing text...\n";\nclose($fh);\n```Remember: "chomp eats the newline, chop eats any last char." Always chomp after reading input.
10. How to create a Perl class? How can you call a method?
Show answer
- Let's create the package: `Example.pm````\npackage Example;\n\nsub new {\n my $class = shift;\n my $self = {};\n bless $self, $class;\n return $self;\n}\n\nsub is_working {\n print "Working!";\n}\n\n1;\n```
- Now we can instance the `Example` class and call `is_working` method:
```\nmy $e = new Example();\n$e->is_working();\n# Output: Working!\n```
11. How can you read a file and print every line?
Show answer
```\nopen(my $fh, '<', 'file_to_read.ext') or die "Error: file can't be opened";\nmy @file = <$fh>;\nforeach my $line (@file) {\n print $line;\n}\n```We can use the file handle without assigning it to an array:
```\nopen(my $fh, '<', 'file_to_read.ext') or die "Error: file can't be opened";\n\nforeach my $line (<$fh>) {\n print $line;\n}\n```
12. Extract hh:mm:ss with capturing group () in the following datetime
Show answer
```\nmy $date = "Fri Nov 19 20:09:37 CET 2021";\nmy @matches = $date =~ /(.*)(\d{2}:\d{2}:\d{2})(.*)/;\nprint $matches[1];\n# Output: 20:09:37\n```Remember: "$_ is Perl's 'it' pronoun." Many functions default to $_ when no argument is given. Example: for (@items) { print; } prints each item because print defaults to $_.
13. Replace the word amazing
Show answer
```\nmy $string = "Perl is amazing!";\n$string =~ s/amazing/incredible/;\nprint $string;\n# Perl is incredible!\n```Remember: "Perl hash = key-value store." Declared with %. Access with $hash{key}. Use keys/values/each to iterate.
14. Does Perl have inheritance? What is the SUPER keyword?
Show answer
Yes, Perl supports inheritance. We can read about it in the official [docs](https://perldoc.perl.org/perlobj#Inheritance).We also can read about `SUPER` keyword that is used to call a method from the parent class. It gives an example about how we can apply inheritance.
Gotcha: Perl has no boolean type — 0, "", "0", and undef are all false. Everything else is true.
15. Does Perl have conventions?
Show answer
You can check [perlstyle](https://perldoc.perl.org/perlstyle)Example: perl -i.bak -pe 's/foo/bar/g' *.txt — replaces foo with bar in all .txt files, creating .bak backups.
Gotcha: -i without extension on some systems destroys the original with no backup.
🔴 Hard (8)¶
1. Does Perl have polymorphism? What is method overriding?
Show answer
Yes, it has polymorphism. In fact method overriding is a way to apply it in Perl.Method overriding in simple words appears when we have a class with a method that already exist in a parent class.
Example:
```\npackage A;\n\nsub new { return bless {}, shift; };\nsub printMethod { print "A\n"; };\n\npackage B;\n\nuse parent -norequire, 'A';\n\nsub new { return bless {}, shift; };\nsub printMethod { print "B\n"; };\n\nmy $a = A->new();\nmy $b = B->new();\n\nA->new()->printMethod();\nB->new()->printMethod();\n\n# Output:\n# A\n# B\n```
2. Using Open3: Create a file with the size of 15MB and check it's created successfully
Show answer
- Code:```\nuse IPC::Open3;\nuse Data::Dumper;\n\nsub execute_command {\n my @command_to_execute = @_;\n my ($stdin, $stdout, $stderr);\n eval {\n open3($stdin, $stdout, $stderr, @command_to_execute);\n };\n if ($@) {\n print "Error. Details: $@";\n }\n close($stdin);\n return $stdout;\n}\n\nmy $file_name = 'perl_open3_test';\n&execute_command('truncate', '-s', '15M', $file_name);\nmy $result = &execute_command('stat', '-c', '%s', $file_name);\nprint Dumper(<$result>);\n```
- Result:
```\n$ -> perl command.pl \n$VAR1 = '15728640\n';\n```
3. How can you iterate an array? And a hash?
Show answer
- Array:```
my @numbers = qw/1 2 3 4 5/;
# Using `$_` that represents the current iteration in a loop. It starts from index array 0 until the last index.
foreach (@numbers) {
print($_);
}
# Output: 12345
# "$#" returns the max index of an array. That's the reason because we can iterate accessing to the array from the index 0 to the max index.
for my $i (0..$#numbers) {
print($numbers[$i]);
}
# Output: 12345
# Using the `map` keyword:
print map {$_} @numbers;
# Output: 12345
# Using `while`. We should take care with this option.
4. Print all the linux system users that starts with d or D
Show answer
- With a Perl one liner :D```\nopen(my $fh, '<', '/etc/passwd');\nmy @user_info = <$fh>;\nmap { print $& . "\n" if $_ =~ /^d([^:]*)/ } @user_info;\nclose $fh;\n```
- Avoiding one-liners
```\nforeach my $user_line (@user_info) {\n if ($user_line =~ /^d([^:]*)/) {\n print $& . "\n";\n }\n}\n```
5. Mention the different modes in File Handling
Show answer
- Read only: `<`- Write mode. It creates the file if doesn't exist: `>`
- Append mode. It creates the file if doesn't exist: `>>`
- Read and write mode: `+<`
- Read, clear and write mode. It creates the file if doesn't exist: `+>`
- Read and append. It creates the file if doesn't exist: `+>>`
6. What data types Perl has? And how can we define it?
Show answer
- Scalar: This is a simple variable that stores single data items. It can be a string, number or reference.```\nmy $number = 5;\n```
- Arrays: This is a list of scalars.
```\nmy @numbers = (1, 2, 3, 4, 5);\n# or using the `qw` keyword (quote word):\nmy @numbers = qw/1 2 3 4 5/; \n# '/' can be another symbol, e.g qw@1 2 3 4 5@\n```
- Hashes (or associative arrays): This is an unordered collection of key-value pairs. We can access to a hash using the keys.
```\nmy %numbers = (\n First => '1',\n Second => '2',\n Third => '3'\n);\n```
7. Does Perl have support for OOP?
Show answer
From the official [docs](https://perldoc.perl.org/perlootut):"By default, Perl's built-in OO system is very minimal, leaving you to do most of the work."
Fun fact: Perl's motto is "There's More Than One Way To Do It" (TMTOWTDI, pronounced "tim-toady").
8. Describe the different ways to receive parameters in a subroutine
Show answer
- List assignment: Using the `@_` array. It's a list with the elements that are being passed as parameters.```\nsub power {\n my ($b, $e) = @_;\n return $b ** $e; \n}\n\n&power(2, 3);\n```
- Individual assignment: We should access to every element of the `@_` array. It starts from zero.
```\nsub power {\n my $b = $_[0];\n my $e = $_[1];\n return $b ** $e; \n}\n\n&power(2, 3);\n```
- Using `shift` keyword: It's used to remove the first value of an array and it's returned.
```
sub power {
my $b = shift;
my $3 = shift;
return $b ** $e;
}
\