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?

Answer:

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;

=pod
This is a multi-line comments 
more...
more...
=cut

print "Hello";
Dec 022010
 

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
Nov 252010
 

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.

Nov 212010
 

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?

Nov 152010
 

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