Perl working tips

Cool tool to test regular expression

Great tool to try regular expression: EditPad Pro (only need the demo version)

Regular expression (re) notes:

Basic syntax:

if (/your-re/)
Alternate syntax:
if (m|your-re|) – note that | can be replaced by any character !
Multi-line:
if (m|
your
multi-line
re
|x)
Putting grouping-parentheses :
if (m|something (?:one|two)+ anything|) – now you have one or two can appear at least one ! (normally you can have only one+ or two+)
Those are tips that would help you work with re much more easily!

Some quick notes

Remove leading and trailing spaces: $string =~ s/^\s+|\s+$// ;
Access the command line arguments: use $ARGV[0], $ARGV[1], …
Open new text file to write:

open FILE, “>filename” ;
print FILE “file content”;
close FILE ;

Search & replace:

$string =~ s/regex/replacement/g

(end).

How to run Linux-shell-command in Perl & get the result ?

Run shell command:
Source: Perl run shell command -> Run Shell COmmand in Perl SCript
From above URL, the answer for running shell command is the system function of Perl.

Get the shell-command result:
Source: Perl run shell command -> Live Search: perl shell command get output
There, they said, there are three basic ways of running external commands:

  • system $cmd;  # using system()
  • $output = `$cmd`; # using backticks (``)
  • open (PIPE, "$cmd |"); # using open()

I myself prefer the backsticks syntax to get the command’s output most, so convenient! Specifically, I wrote the following to get RAM’s free size :

my $cmd=”cat /proc/meminfo | grep MemFree” ;
my $memFree = `$cmd` ;#note the backsticks ` not the ‘ !
$memFree =~ s/
^\D+ (\d+) \D+$
/$1/x ;

What a found!

Notes about arguments when using sub in Perl!

Source: I try it myself!

Assumed we have the code :

#this is where mySub called
my $outside=123 ;
sub mySub {
#here don’t see $outside varible !
}

So note that in sub, we can’t use outside-declared variables declared after the call command. Be caution !

How to get Perl ‘s array size ?

Source: google:perl array size-> Array Manipulation in Perl

Assumed having array @arr, to get its size, call either :

  • directly using $# :
    $#arr+1
  • from a indirect-converved varible :
    $size=@arr

Enjoy!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: