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.

How to find a Perl Module's Path

Answer:

For example, we want to know where the module JSON and related modules exist in the local file system, we can try:

# perl -MJSON -e'print $_ . " => " . $INC{$_} . "\n" for keys %INC'

attributes.pm => /usr/share/perl/5.10/attributes.pm
XSLoader.pm => /usr/local/lib/perl/5.10.0/XSLoader.pm
warnings/register.pm => /usr/share/perl/5.10/warnings/register.pm
Carp.pm => /usr/share/perl/5.10/Carp.pm
Exporter/Heavy.pm => /usr/share/perl/5.10/Exporter/Heavy.pm
common/sense.pm => /usr/local/share/perl/5.10.0/common/sense.pm
vars.pm => /usr/share/perl/5.10/vars.pm
Exporter.pm => /usr/share/perl/5.10/Exporter.pm
strict.pm => /usr/share/perl/5.10/strict.pm
constant.pm => /usr/local/share/perl/5.10.0/constant.pm
warnings.pm => /usr/share/perl/5.10/warnings.pm
JSON/XS.pm => /usr/local/lib/perl/5.10.0/JSON/XS.pm
overload.pm => /usr/share/perl/5.10/overload.pm
base.pm => /usr/share/perl/5.10/base.pm
JSON.pm => /usr/local/share/perl/5.10.0/JSON.pm

How to get the full list of Ubuntu's managed Perl modules?

Answer:

The full list of Ubuntu's managed Perl modules is here (for lucid): http://packages.ubuntu.com/lucid/perl/

You can use apt-get into install those modules, instead of CPAN. The advantage is you can remove them easier with the apt-get command, while for CPAN, you need to do it manually.

Write to the middle of a file in Perl

Answer:

To write to the middle of a text file, can be easily performed by Perl.

Assume the file has 10 lines, you want to replace the 5th line:

#!/usr/bin/perl
use strict;
use Tie::File;

my $file = 'foo.txt';

tie @array, 'Tie::File', $file or die "Cannot open $file \n";

@array[4] = "Replaced!\n";

That's easy?

What is the difference between || and or in Perl?

Answer:

In Perl, sometimes you can use both `||` and `or` to to do the same thing. But the main different is:

  • or has very low precedence, which is useful for flow control

Example:

open FILE,  $file or die("Cannot open $file");   # Work
open FILE,  $file || die("Cannot open $file");   # Does not work , because it it same as the next statement
open FILE, ($file || die("Cannot open $file"));  # Obviously not work

Pass hash as reference in Perl

Answer:

In the previous post, we talked about how to Pass hash as list in Perl, now we discuss another way: To pass a hash as a reference in Perl function.

sub foo {

    my ($h) = @_;

    print $h->{"1"};
}

foo ( {"1" => "One", "2" => "Two"} );

One will be printed out.