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.

Dec 202010

How can I comment out a large block of Perl code?


Perl does not support multi-line comments like C++ or Java. If you want to comment out a large block of Perl code, there is still a trick.

package Foo;

This is a multi-line comments 

print "Hello";
Dec 022010

How to find a Perl Module's Path


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' => /usr/share/perl/5.10/ => /usr/local/lib/perl/5.10.0/
warnings/ => /usr/share/perl/5.10/warnings/ => /usr/share/perl/5.10/
Exporter/ => /usr/share/perl/5.10/Exporter/
common/ => /usr/local/share/perl/5.10.0/common/ => /usr/share/perl/5.10/ => /usr/share/perl/5.10/ => /usr/share/perl/5.10/ => /usr/local/share/perl/5.10.0/ => /usr/share/perl/5.10/
JSON/ => /usr/local/lib/perl/5.10.0/JSON/ => /usr/share/perl/5.10/ => /usr/share/perl/5.10/ => /usr/local/share/perl/5.10.0/
Nov 252010

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


The full list of Ubuntu's managed Perl modules is here (for lucid):

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.

Nov 212010

Write to the middle of a file in Perl


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:

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?

Nov 152010

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


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


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