Perl Regex named capture variables

Simple example to extract, protocol, server and domain from a given URL:

my $test = "http:www.test.com";

$test =~ /^(?<protocol>.+)\:(?<server>.+)\.(?<domain>.+)$/;

print "protocol : ".$+{protocol}."\n";
print "Server   : ".$+{server}."\n";
print "Domain   : ".$+{domain}."\n";

Our Result:

sh-4.3$ perl main.pl 
protocol : http      
Server   : www.test 
Domain   : com

Perl find all pow 2 numbers

This little script finds all pow 2 numbers in Perl :

use strict;
my $number = 0;

for(1..32){
    ++$number;
    print "$number - ".isPow2($number)."\n";
}


sub isPow2 {
    return(0) if($_[0] <= 0);
    return(1) if($_[0] == 1);
    for(1..$_[0]){
       return(1) if($_[0] == 2**$_)
    }
    return(0);
}

Our Result:

1 - 1  
2 - 1  
3 - 0  
4 - 1  
5 - 0  
6 - 0  
7 - 0  
8 - 1  
9 - 0  
10 - 0 
11 - 0 
12 - 0 
13 - 0 
14 - 0 
15 - 0 
16 - 1

Perl print String difference

This function prints the difference between two strings with Perl:

sub printStringDiff{
my ($s1, $s2) = @_;

my @s1 = split(//, $s1);
my @s2 = split(//, $s2);
while (@s1) {

    if (defined $s1[0] and defined $s2[0]) {
    	if($s1[0] eq $s2[0]){
			print shift @s1;
		}else{
			print color("red"),shift @s1, color("reset");
		}
    }elsif(defined $s1[0]){
    	print color("red"),shift @s1, color("reset");
    }
    shift @s2;
}
print "\n";

@s1 = split(//, $s1);
@s2 = split(//, $s2);
while (@s2) {

    if (defined $s2[0] and defined $s1[0]) {
		if($s2[0] eq $s1[0]){
			print shift @s2;
		}else{
			print color("red"),shift @s2, color("reset");
		}
    }elsif(defined $s2[0]){
    	print color("red"),shift @s2, color("reset");
    }
    shift @s1;
}
print "\n";
}

You need the Module Term::ANSIColor, to highlight the changes,use it like this:

#!/usr/bin/perl
use strict;
use Term::ANSIColor;

printStringDiff("1234","123456");
print "\n";

printStringDiff("123456","1234");
print "\n";

printStringDiff("ABAA","AABA");
print "\n";

And the Result is :

ColorStringDiff

Perl check if file handler is open

If you write a function in Perl and want to check if the file handler is already open you could use this function:

sub filehandlerOpen {
	my $fh = shift;
	no warnings 'uninitialized';
	return 0 if(!defined $fh || $fh !~ /^GLOB\(0x.+?\)$/);
	if(fileno($fh) >= 1){
		return(1);
	}
	return(0);
}

It returns 0 if its undefined,closed or not open, an 1 if the handler is open.

 

In this little example I open a file to read and another to write, I check the sub before and after the open function, and before and after the close function.

#!/usr/bin/perl
use warnings;
use strict;

my ($fh_read,$fh_write);

print "Check undefined:\n";
print filehandlerOpen($fh_read).$/;
print filehandlerOpen($fh_write).$/;


open($fh_write, ">", './testfile') or die "Failed to open file: $!\n";
open($fh_read, "<", './testfile') or die "Failed to open file: $!\n";


print "Check defined:\n";
print filehandlerOpen($fh_read).$/;
print filehandlerOpen($fh_write).$/;


for my $num (1..6){
	print $fh_write "$num\n";
}
print "Check close write:\n";
print filehandlerOpen($fh_write).$/;
close($fh_write);
print filehandlerOpen($fh_write).$/;


while (my $row = <$fh_read>) {
  chomp $row;
}
print "Check close read:\n";
print filehandlerOpen($fh_read).$/;
close($fh_read);
print filehandlerOpen($fh_read).$/;


sub filehandlerOpen {
	my $fh = shift;
	no warnings 'uninitialized';
	return 0 if(!defined $fh || $fh !~ /^GLOB\(0x.+?\)$/);
	if(fileno($fh) >= 1){
		return(1);
	}
	return(0);
}

The Result, looks like expected:

Check undefined:
0
0
Check defined:
1
1
Check close write:
1
0
Check close read:
1
0

Perl print __DATA__ multiple times

Sometimes you have a lot of Data in Perl and you want to store in your script, for that you could you the __DATA__ token, you could simple read it with a file handle:

print <DATA>,"\n";

__DATA__
Test String
123456

If you use it more than one time you should seek for the start position:

#!/usr/bin/perl
use warnings;
use strict;



my $data_start = tell DATA; # where __DATA__ begins
print <DATA>,"\n";
seek DATA, $data_start, 0;

print <DATA>,"\n";

__DATA__
Test String
123456

Output looks like this:

Test String
123456

Test String
123456

Perl read/write File

This is a simple example how to write into a File with Perl, and then read from it.At first we write the numbers from 1 to 6 into the file, in the second we read from the file and print it on the screen, if you don’t want the “\n” at the end use the function chomp.

If you open a File for read use ‘<‘, for write ‘>’ and for append ‘>>’.

#!/usr/bin/perl
use warnings;
use strict;

#declare filehandler
my ($fh_read,$fh_write);


#open file for write
open($fh_write, ">", './testfile') or die "Failed to open file: $!\n";

#now write
for my $num (1..6){
	print $fh_write "$num\n";
}

#close the file
close($fh_write);


#open file for read
open($fh_read, "<", './testfile') or die "Failed to open file: $!\n";

#now read
while (my $row = <$fh_read>) {
  print $row;
}

#close the file
close($fh_read);

Result looks like:

1
2
3
4
5
6

you could check if a handler is open with this Perl handler function.

Fraction calculation in Perl

This Perl script is able to add,subtract,divide and multiply fractional numbers:

use strict;
#test data:
my @B1 = _read();
my @B2 = _read();
#test addition
my @BC = _add(@B1,@B2);
print "+:",_print(@BC);
# test substract
   @BC = _sub(@BC,@B2);
print "-:",_print(@BC);
#simplify the result
   @BC = simplify(@BC);

#test multiplication
   @BC = _mul(@B1,@B2);
print "*:",_print(@BC);
#test division
   @BC = _div(@BC,@B2);
print "/:",_print(@BC);
#simplify the result
   @BC = simplify(@BC);

sub _add {
    my $gn = $_[1]*$_[3];
    return(($_[0]*($gn/$_[1]))+($_[2]*($gn/$_[3])),$gn);
}

sub _sub {
    my $gn = $_[1]*$_[3];
    return(($_[0]*($gn/$_[1]))-($_[2]*($gn/$_[3])),$gn);
}

sub _mul {
    return($_[0]*$_[2],$_[1]*$_[3]);
}

sub _div {
    return($_[0]*$_[3],$_[1]*$_[2]);
}

sub _print {
    my @D = &simplify;
    my $c = 0;
    while(1){
        if($D[0]>=$D[1]){
            $D[0] -= $D[1];
            ++$c;
        }else{
            last;    
        }
    }
    if($c){
        return "$c+$D[0]/$D[1](".&fractial2number.")\n"; 
    }else{
        return "$D[0]/$D[1](".&fractial2number.")\n"; 
    }
}

sub _read {
    print "fractal number:";
    my $in = <STDIN>;
    if($in =~ /\//o){
       $in =~ /^(.+)\/(.+)$/o;
        return($1,$2);
    }else{
       return(number2fractial($in)); 
    }
}

sub number2fractial {
    $_[0] =~ /^(.+)\.(.+)$/o;
    my $d = $1;
    my $c = $2;
    my $u = $2;
       $u =~ s/./0/g;
       $u = "1".$u;
    return($c+($d*$u),"$u");
}

sub fractial2number {
    return($_[0]/$_[1]);
}

sub simplify {
    for($_ = $_[1];$_>=2;--$_){
        return($_[0]/$_,$_[1]/$_) if($_[0]%$_==0 && $_[1]%$_==0);
    }
    return($_[0],$_[1]);
}

This is the output from 1/2 and 1.25, at first add both then subtract from the result, multiply and then divide from the result:

fractal number:1/2  
fractal number:1.25 
+:1+3/4(1.75)       
-:1/2(0.5)          
*:5/8(0.625)        
/:1/2(0.5)

For a better result take a look at Perl high precision.

JavaScript generate an result array from XPATH

This is a function in JavaScript that use an XPATH string to generate an Array from the results.This is very useful if you have to manipulate or use some items on a page and don’t have the id(like bots).

That is the function:

function matches2array (XPATH){
  var links = new Array();
  var elements = 0;
  var xPathRes = document.evaluate (XPATH, document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
  var actualSpan = xPathRes.iterateNext ();
  while (actualSpan) {
    links[elements] = actualSpan;
    actualSpan = xPathRes.iterateNext ();
    ++elements;
  }
  return(links);
}

You could use it in the Terminal:

matches2array("//a");

And we get all hrefs on this page in the Terminal:

[a.skip-link.screen-reader-text #content, a scheinast.eu, a /category/c-sharp/, a /category/c/, a /category/fortran/, a /category/bash/, a /category...-css-js/, a /category/java/, a /category/perl/, a /category/php/, a /category/projects/, a /category/regex/, a /category...-tricks/, a /category/windows/, a /perl-str...nchmark/, a /regex-fi...strings/, a /how-to-o...desktop/, a /c-calculator/, a /javascri...ocation/, a /image-uploader/, a /wp-admin/, a wp-login....68d8990f, a /feed/, a /comments/feed/, a wordpress.org, a.a2a_button_facebook /, a.a2a_button_twitter /, a.a2a_button_google_plus /, a.a2a_dd.addtoany_share_save share_sav...2F%5D..., a /calculator-in-c/, a.url.fn.n /author/p...heinast/, a /category/c/, a /tag/c/, a /tag/calculator/, a.post-edit-link post.php?...ion=edit, a#cancel-comment-reply-link /calculat...#respond, a profile.php, a wp-login....68d8990f, a /new-hompage-design/, a /backtrack-how-to/, a.a2a_button_facebook /, a.a2a_button_twitter /, a.a2a_button_google_plus /, a.a2a_dd.addtoany_share_save share_sav...2F%5D..., a.screen-reader-shortcut #wp-toolbar, a.ab-item about.php, a.ab-item about.php, a.ab-item wordpress.org, a.ab-item codex.wordpress.org, a.ab-item /support/, a.ab-item requests-...feedback, a.ab-item admin.php...tics.php, a.ab-item admin.php...ine_menu, a.ab-item admin.php...tics.php, a.ab-item /wp-admin/, a.ab-item /wp-admin/, a.ab-item themes.php, a.ab-item customize...D=themes, a.ab-item customize...-in-c%2F, a.ab-item widgets.php, a.ab-item customize...=widgets, a.ab-item nav-menus.php, a.ab-item themes.ph...ckground, a.ab-item customize...nd_image, a.ab-item themes.ph...m-header, a.ab-item customize...er_image, a.ab-item edit-comments.php, a.ab-item post-new.php, a.ab-item post-new.php, a.ab-item media-new.php, a.ab-item post-new....ype=page, a.ab-item user-new.php, a.ab-item post.php?...ion=edit, a.ab-item profile.php, a.ab-item profile.php, a.ab-item profile.php, a.ab-item wp-login....68d8990f, a.screen-reader-shortcut wp-login....68d8990f, a.a2a_i.a2a_sss /, a.a2a_i.a2a_sss /, a.a2a_i.a2a_sss /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a, a.a2a_i.a2a_sss /, a.a2a_i.a2a_sss /, a.a2a_i.a2a_sss /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a.a2a_i /, a#a2apage_any_email.a2a_i.a2a_emailer /, a#a2apage_email_client.a2a_i.a2a_emailer.a2a_email_client /, a#a2apage_show_more_less.a2a_menu_show_more_less.a2a_more]

Use it to store it in an Array and then write it on the page:

var scripts = matches2array("//a");

for (i=0;i<scripts.length;i++){
document.write(scripts[i] + "\n");
}

and we got this result:

http://scheinast.eu/calculator-in-c/#content http://scheinast.eu/ http://scheinast.eu/category/c-sharp/ http://scheinast.eu/category/c/ http://scheinast.eu/category/fortran/ http://scheinast.eu/category/bash/ http://scheinast.eu/category/html-css-js/ http://scheinast.eu/category/java/ http://scheinast.eu/category/perl/ http://scheinast.eu/category/php/ http://scheinast.eu/category/projects/ http://scheinast.eu/category/regex/ http://scheinast.eu/category/tips-and-tricks/ http://scheinast.eu/category/windows/ http://scheinast.eu/perl-strict-benchmark/ http://scheinast.eu/regex-find-interpolate-strings/ http://scheinast.eu/how-to-open-remote-desktop/ http://scheinast.eu/c-calculator/ http://scheinast.eu/javascript-location/ http://scheinast.eu/image-uploader/ http://scheinast.eu/wp-admin/ http://scheinast.eu/wp-login.php?action=logout&_wpnonce=a768d8990f http://scheinast.eu/feed/ http://scheinast.eu/comments/feed/ https://wordpress.org/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ https://www.addtoany.com/share_save#url=http%3A%2F%2Fscheinast.eu%2Fcalculator-in-c%2F&title=Calculator%20in%20C%2B%2B&description=This%20is%20my%20calculator%20in%20C%2B%2B%20with%20in-line%20assembler%3A%20%5Bcrayon-556e97ccb93bc417229824%2F%5D%20Compile%20the%20code%3A%20%5Bcrayon-556e97ccb93e1826855153%2F%5D%20output%3A%20%5Bcrayon-556e97ccb93f8566053665%2F%5D... http://scheinast.eu/calculator-in-c/ http://scheinast.eu/author/paul-scheinast/ http://scheinast.eu/category/c/ http://scheinast.eu/tag/c/ http://scheinast.eu/tag/calculator/ http://scheinast.eu/wp-admin/post.php?post=1542&action=edit http://scheinast.eu/calculator-in-c/#respond http://scheinast.eu/wp-admin/profile.php http://scheinast.eu/wp-login.php?action=logout&redirect_to=http%3A%2F%2Fscheinast.eu%2Fcalculator-in-c%2F&_wpnonce=a768d8990f http://scheinast.eu/new-hompage-design/ http://scheinast.eu/backtrack-how-to/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ https://www.addtoany.com/share_save#url=http%3A%2F%2Fscheinast.eu%2Fcalculator-in-c%2F&title=Calculator%20in%20C%2B%2B%20%7C%20Paul%20Scheinast&description=This%20is%20my%20calculator%20in%20C%2B%2B%20with%20in-line%20assembler%3A%20%5Bcrayon-556e97ccb93bc417229824%2F%5D%20Compile%20the%20code%3A%20%5Bcrayon-556e97ccb93e1826855153%2F%5D%20output%3A%20%5Bcrayon-556e97ccb93f8566053665%2F%5D... http://scheinast.eu/calculator-in-c/#wp-toolbar http://scheinast.eu/wp-admin/about.php http://scheinast.eu/wp-admin/about.php https://wordpress.org/ https://codex.wordpress.org/ https://wordpress.org/support/ https://wordpress.org/support/forum/requests-and-feedback http://scheinast.eu/wp-admin/admin.php?page=wp-statistics/wp-statistics.php http://scheinast.eu/wp-admin/admin.php?page=wps_online_menu http://scheinast.eu/wp-admin/admin.php?page=wp-statistics/wp-statistics.php http://scheinast.eu/wp-admin/ http://scheinast.eu/wp-admin/ http://scheinast.eu/wp-admin/themes.php http://scheinast.eu/wp-admin/customize.php?url=http%3A%2F%2Fscheinast.eu%2Fcalculator-in-c%2F&autofocus%5Bsection%5D=themes http://scheinast.eu/wp-admin/customize.php?url=http%3A%2F%2Fscheinast.eu%2Fcalculator-in-c%2F http://scheinast.eu/wp-admin/widgets.php http://scheinast.eu/wp-admin/customize.php?url=http%3A%2F%2Fscheinast.eu%2Fcalculator-in-c%2F&autofocus%5Bpanel%5D=widgets http://scheinast.eu/wp-admin/nav-menus.php http://scheinast.eu/wp-admin/themes.php?page=custom-background http://scheinast.eu/wp-admin/customize.php?url=http%3A%2F%2Fscheinast.eu%2Fcalculator-in-c%2F&autofocus%5Bcontrol%5D=background_image http://scheinast.eu/wp-admin/themes.php?page=custom-header http://scheinast.eu/wp-admin/customize.php?url=http%3A%2F%2Fscheinast.eu%2Fcalculator-in-c%2F&autofocus%5Bcontrol%5D=header_image http://scheinast.eu/wp-admin/edit-comments.php http://scheinast.eu/wp-admin/post-new.php http://scheinast.eu/wp-admin/post-new.php http://scheinast.eu/wp-admin/media-new.php http://scheinast.eu/wp-admin/post-new.php?post_type=page http://scheinast.eu/wp-admin/user-new.php http://scheinast.eu/wp-admin/post.php?post=1542&action=edit http://scheinast.eu/wp-admin/profile.php http://scheinast.eu/wp-admin/profile.php http://scheinast.eu/wp-admin/profile.php http://scheinast.eu/wp-login.php?action=logout&_wpnonce=a768d8990f http://scheinast.eu/wp-login.php?action=logout&_wpnonce=a768d8990f http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ https://www.addtoany.com/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/ http://scheinast.eu/calculator-in-c/