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.

Nov 042010
 

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.

Nov 012010
 

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..

Oct 302010
 

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.

Oct 132010
 

Is Perl pass by reference or pass by value?

Answer:

(Edit: Thanks Matt for the feedback, I have updated the answer.)

It depends on how your function is implemented

See the code below:


package Dog;

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

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

// Pass by reference
sub Bar {
	$_[0] = new Dog("Another");
}

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

Foo($d); // Pass by value, $d not changed, so it print out "Peter"
print $d->{"name"};

Bar($d); // Pass by reference, $d is changed, so it print out "Another"
print $d->{"name"};