Pass hash as list in Perl
Answer:
To pass a hash as a list in Perl function, use the following way:
use strict;
use warnings;
sub foo {
my %h = @_;
print $h{1};
}
foo ( 1 => "One", 2 => "Two" );
One will be printed out.
Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.
Pass hash as list in Perl
Answer:
To pass a hash as a list in Perl function, use the following way:
use strict;
use warnings;
sub foo {
my %h = @_;
print $h{1};
}
foo ( 1 => "One", 2 => "Two" );
One will be printed out.
Force Perl to use integer arithmetic
Answer:
To force Perl to use integer arithmetic, instead of floating point, you just need to add the statement "use integer;" at the beginning of your script.
Example:
use strict;
use warnings;
use integer;
my $i = 10/3;
print $i;
It above program will print out 3 instead of 3.333..
Return the last evaluated statement from function in Perl
Answer:
By default, Perl does not require you to explicit return the the last evaluated statement from function.
E.g.
print function1();
sub function1 {
my $i = 99;
}
The above program will output 99, and you can see the return statement is not needed and it is a valid Perl program.
Generate a random number in Python
Answer:
It is very easy to generate a random number in Python, see below:
import random
print random.randint(1,100)
The above code print a number between 1 to 100.
Multi-line string in Python
Answer:
In Python, multi-line string are enclosed in triple double (or single) quotes:
E.g.
s = """Line1
Line2
Line3"""
print s
Or
s = '''Line1
Line2
Line3'''
print s
Both methods are valid.