Linux Ask!

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.

Is Perl pass by reference or pass by value?

Answer:

Pass by value.

See the code below:


package Dog;

sub new {
	my ($class, $name) = @_;
	my $self = { "name" => $name };
	bless $self, $class;
	return $self;
}

sub Foo {
	my $d = shift;
	$d = new Dog("Another");
}

my $d = new Dog("Peter");

Foo($d);

print $d->{"name"};

If Perl is pass by reference, the variable "name" would be changed to "Another" inside the function Foo().

Delete element in a hash in Perl

Answer:

You can use the delete keyword to delete elements in a hash in Perl

my $hash = {
                "one" => 1,
                "two" => 2,
                "three" => 3
        };

delete $hash->{"two"};