kris004 has asked for the wisdom of the Perl Monks concerning the following question:
So, I decided to learn some Perl earlier today. I had a small script that downloaded and converted a hosts file for use with unbound:
#!/bin/sh curl https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts +|grep '^0\.0\.0\.0' | awk '{print "local-zone: \""$2"\" redirect\nloc +al-data: \""$2" A 0.0.0.0\""}' > ads.conf
Which discards all lines except lines like this:
0.0.0.0 apps.id.netAnd changes it into two lines like this:
local-zone: "apps.id.net" redirect local-data: "apps.id.net A 0.0.0.0"
I poked around this site and read some docs and came up with this:
#!/usr/bin/perl use strict; use warnings; use LWP::Simple; my $url = "https://raw.githubusercontent.com/StevenBlack/hosts/master/ +hosts"; open(my $file, '>', 'ads.conf') or die "wtfile?"; for (split /^/, get ($url)) { if ($_ =~ /0\.0\.0\.0/ and $_ !~ /#/){ $_ =~ s/0\.0\.0\.0 //; $_ =~ s/\n//; print $file "local-zone: \"" . $_ . "\" redirect\nloca +l-data: \"" . $_ . " A 0.0.0.0\"\n"; } } close $file;
Turns out the Perl script takes 5 times as long as the shell script, and uses nearly twice the cpu. What mistakes did I make, and is there a way to do this in Perl faster then the shell script can?
Updated script based on comments:
#!/usr/bin/perl use strict; use warnings; use LWP::Simple; my $url = "https://raw.githubusercontent.com/StevenBlack/hosts/master/ +hosts"; open(my $file, '>', 'ads.conf') or die "wtfile?"; for (split /^/, get ($url)) { if ($_ =~ /^\Q0.0.0.0\E (.*)$/){ print $file "local-zone: \"" . $1 . "\" redirect\nloca +l-data: \"" . $1 . " A 0.0.0.0\"\n"; }
Update 2, thank you marioroy (link) and rizzo (link), combining your two suggestions gets me the fastest script so far:
#!/usr/bin/perl use strict; use warnings; my $_url = "https://raw.githubusercontent.com/StevenBlack/hosts/master +/hosts"; open(my $file, '>', 'ads.conf') or die "wtfile?"; my $var = `curl $_url` or die "wturl?"; while($var =~ /(\n0\.0\.0\.0)(\s)([\w\.]+?)\s+/g){ print $file "local-zone: \"" . $3 . "\" redirect\nlocal-data: +\"" . $3 . " A 0.0.0.0\"\n"; } close $file;
Interestingly that script, seems to be on par with the shell script time wise, but does it using 1/6th the cpu.
|
---|