https://stackoverflow.blog/2022/07/06/why-perl-is-still-relevant-in-2022/
*
Essays, opinions, and advice on the act of computer programming from
Stack Overflow.
Search for: [ ] [Search]
Latest Newsletter Podcast Company
[290622-Stack-Overflow-Why-Perl-is-still-relevant-in-2022-1200x630]
code-for-a-living July 6, 2022
Why Perl is still relevant in 2022
While Perl might seem like an outdated scripting language, it still
has plenty of relevant uses today.
Avatar for
Girish Venkatachalam
If you love UNIX/Linux/BSD like me, then you have definitely learnt
Perl and programmed in it. I am pretty certain you have also used
Perl more than once, perhaps several times. The language was created
in 1987 as a general purpose UNIX scripting language, but has
undergone many changes since then (even spawning another programming
language, Raku).
You may have used it for occasional sys admin tasks, in your tool
chain, or to enhance some shell scripts that needed more gas. But
Perl is more than just scripting.
But from the amount of talk about Perl on Reddit or Stack Overflow,
you might think it's dead. It's far from dead, and is still very
relevant to software engineering today.
20092010201120122013201420152016201720182019202020212022Year0.00%0.50%1.00%1.50%2.00%2.50%3.00%3.50%4.00%%
of Stack Overflow questions that monthTagnode.jsperlbash
From https://insights.stackoverflow.com/trends?tags=
perl%2Cbash%2Cnode.js
What makes it special?
Perl is a high-level language. It is weakly typed , has synchronous
flow, and is an interpreted language. It has garbage collection and
excellent memory management. Perl 5 is open source and free to
contribute to.
Perl's primary strength is in text processing. Be it a regex-based
approach or otherwise, Perl is excellent for logfile analysis, text
manipulation, in-place editing of files, and scouring structured text
files for specific field values.
Perl is very UNIX-friendly. Perl serves as a wrapper around UNIX
tools and is fully integrated into OS semantics. Other languages
don't attempt this. As a result, it excels at pipes, file slurping,
inter-process communication and other geeky tasks. Like C, it can
create UNIX daemons or server processes that run in the background.
We can easily invoke a Perl daemon to avoid spending hours working on
C and avoid several security flaws.
Like npm for node.js, Perl has a vibrant development community in
CPAN, with a vast archive of Perl modules. You can find a module to
do anything you want. Most modules are written in pure Perl without
resorting to C, though some performance intensive modules have an XS
component that uses C for performance.
Through CPAN, you can wrap many databases--SQLite, MySQL, Postgres,
and more--in Perl code using database driver (DBD) modules. These
export the DB operations using Perl's own semantics into unified
portable Perl code that hides the complexities of the database.
Perl supports arrays, hashes, and references using which you can code
in very powerful ways without thinking deeply about data structures
or algorithms. Most CPAN modules give you both a functional style as
well as the object oriented one. By giving you that choice, you can
pretty much do your task your own way.
What sort of problems make Perl a natural?
As stated above, Perl does very well with text processing. It can
scour CSV files for data fields based on complex regex statements. It
can quickly parse logfiles. It can quickly edit settings files. Perl
is also a natural for various format conversions, generating PDFs,
HTML, or XML.
In early days of the internet, Perl served as the foundation of a lot
of basic networking tasks: common gateway interface (CGI), MIME
decoding in emails, even opening websockets between a client and
server. It still excels here, and can handle networking tasks without
running a whole server application.
For power UNIX users, Perl lets you automate nearly any action that
you like. You can create daemons--small, constantly running
programs--that will automatically take actions when their conditions
are met. You can even create build pipelines and automate unit tests
.
A simpler way to code
In today's event-loop-centric asynchronous world of JavaScript,
node.js, and TypeScript, Perl offers a very straight-forward code
flow, and Perl code offers simplicity and control.
The fact that code flows synchronously makes a big difference in
debugging and getting started writing working code. Perl has
supported threads for long time, but I have never used them.
Perl is best run in single tasks--on its own, it is not a language
with great performance. If you wanted performance today, you have
JavaScript and C, except with added complexity and debugging
nightmares.
Perl includes a number of specialized operators that process data in
unique ways. You can use the diamond <> operator to eat up any
stream, file, socket, pipe, named pipe, whatever.
The regex operator =~ means regular expressions can be included in
functions very easily.
Perl emphasizes the get what you want the way you want philosophy.
Let us examine some code samples to get some perspective.
Let us say we have to create a sha256 digest of a string.
This is how you do in node.js:
This is how you do in node.js.
const {
createHash
} = require('node:crypto');
const hash = createHash('sha256');
data = 'Stack Overflow is cool';
hash.update(data);
console.log(hash.copy().digest('hex'));
In Perl there are two ways. One is the functional approach:
use Digest::SHA qw(sha256_hex);
$data = 'Stack Overflow is cool';
$hexdigest = sha256_hex($data);
print("Functional interface :: " . $hexdigest . "\n");
Another is the object-oriented approach:
$sha = Digest::SHA->new('sha256');
$sha->add($data); # feed data into stream
$hexdigest = $sha->hexdigest;
print("OO interface ::" . $hexdigest);
Here's how you do it in Python:
import hashlib
m = hashlib.sha256()
m.update(b"Stack Overflow is cool")
print(m.hexdigest())
Garbage collection
For a language mostly considered only good for scripting, it has
garbage collection. It's a simple form called reference counting,
where Perl counts the number of references to a variable and reclaims
those variables if there are no more references (or if a program
leaves the scope that a variable was created in). There is no C
monstrosity of having to free() and mind all your malloc() calls.
There is also no stack overflow hell as with node.js, in which an
unintended closure results in recursion and crash.
You can always use the die() diagnostic tool or the Data::Dumper to
figure out causes in case something does not go as planned. Perl can
be run in debug mode with the -d switch, but I have hardly used it.
Now let us contrast Perl with some other popular languages to get a
context.
Comparing Perl to other languages
Now let us compare Perl to other languages once again. What about non
blocking socket I/O or file read? What about dealing with big data?
What about binary data?
In all these departments Perl has its muscles to flex. For binary
data however, you are much better off with C or something. Perl does
have ord, pack, and friends. But for text based protocols like SMTP,
HTTP, and the like, Perl socket I/O is quite nice. Particularly using
the diamond operator, <>, for consuming data from any file
descriptor.
What do these things remind you of...that's right, UNIX. Perl is living
example of how going all the way with UNIX philosophy gets things
done.
People talk of node.js streams and so on, but to me it looks like a
joke compared to the UNIX and Perl world.
Perl is however an easy alternative to insecure PHP. But for some
reason the world does not want to give up on PHP. Perl requires more
knowledge and has a steep learning curve compared to PHP, but Perl is
Perl. You use it anywhere you want and get things done.
Perl vs Python
Python has an interactive shell where you can easily develop code and
learn. It is amazing and really helps language learners. Python
serves as an excellent learner's programming language.
Perl however has a -c switch to just compile the code to check for
basic syntax errors.
Perl has use strict and -w flags which make it more resistant to
unintended variable spelling errors and scoping problems. Python does
not offer that.
Python is an out and out object-oriented paradigm. Perl is a mix.
Python offers several functional programming concepts like lambda,
map, and friends, but it remains rooted in OOP.
Perl is more invested in using traditional references and hash
semantics for subroutines and other advanced usage. Python tries to
do it using objects a little like how node.js does it.
Python has Jupyter notebook that takes the power of Python to the
browser. Python scripts tend to be shorter than Perl in general.
Python has more economic syntax, excellent saving in lines of code by
chaining objects, but Perl shines in other areas.
Sometimes it is not an apples to apples comparison as each
programming language has its own benefits and specific uses.
Perl vs node.js
Node.js is fully object-oriented, but functions are first class
variables, which means you can use a function name any which way you
want and invoke it in creative ways, but this risks confusing
beginners. It is fully asynchronous.
The node.js program flow can be scary for beginners. Even experienced
programmers struggle with code flow and figuring out when a function
returns. It can lead to callback hell, though promises and async/
await make things better--if they are used. But the event loop and
single threaded node.js flow makes it harder to use for one off
tasks.
Perl is pleasant and more straight-forward. Typically, if you wish to
use a third-party library to solve a particular problem, you can
either do it using node.js or Perl. The open source modules for
plugging into most third-party libraries exist for both languages.
Most of the time, node.js relies on package.json and local
installations. Perl depends on system-wide installations of
dependencies or libraries/modules.
Perl vs ksh/bash
Well, this is a funny thing to write. Perl could be a contender for
shell-scripting jobs as it is a scripting language, correct? But Perl
installation is a factor to consider whether to use it or some shell
in a resource-constrained environment like Raspberry Pi or something.
Perl does offer a lot of really nice things lacking in shell scripts,
but this really bears no further discussion. It is not a meaningful
comparison. For instance, we don't compare ksh and Python but tend to
talk about Perl in same context. This is due to its roots. Otherwise,
there is no meaning in this.
Some drawbacks of Perl
While I am a strong supporter of Perl, let us be balanced and examine
why it is not making inroads in certain areas like AI. In today's AI
and ML centric world, Python seems to have made a very strong
footprint.
When it comes to the performance of node.js and its event loop
single-threaded performance, Perl is not a contender.
In the race for performance and modern trends, Perl definitely
appears a bit dated. But it does have a place as we have seen above.
Why it is still relevant in 2022
Perl is not going away. That ain't gonna happen.
It is still being used in CGI scripts. It is used in several sys
admin tasks. Perl is still alive and kicking.
In terms of bindings to other libraries and utilities, Perl is as
good as other choices. For instance, if you wish to talk to libcurl
or libtls or some third-party open-source library, then we can often
choose the language we like. Here, Perl is supported out of the box
and you can easily get your job done.
Perl shines in what it is good at. And as long as the problems it
solves well are not solved by other tools, Perl will continue to
exist and grow.
Conclusion
Perl has always been very remarkable about its documentation and
tutorials--perhaps being too wordy at times--but clearly they are
developer-friendly.
Hopefully this article makes a case for Perl that is convincing and
reasonably objective based on current trends, usage statistics, and
developer base. A programmer is typically influenced by factors that
differ from that of a business need or a manager. In both cases, Perl
makes a case as it offers convenience, quick development times, and
rich community support and tooling.
Bonus: Perl code you can use
MIME decoding example
Here is a MIME decoded that I wrote a while ago. It displays an email
by doing recursive decoding of MIME bodies.
#!/usr/bin/perl
use JSON;
use CGI;
use DBI;
use Sys::Syslog;
use Broker;
use Encode qw/decode/;
use File::Basename;
use MIME::Parser;
use File::Copy;
use File::Glob;
use File::Path;
$q = CGI->new;
print $q->header('application/json');
$json = JSON->new;
@mailBody =();
@mailText =();
openlog("--Show one quamail... :");
my $db = DBI->connect("dbi:Pg:host=/tmp", "postgres", undef, {AutoCommit => 0});
if(!defined($db)) {
print("error","Could not connect to Postgres db");
}
sub dump_entity {
my ($entity, $name) = @_;
defined($name) or $name = "'anonymous'";
my $IO;
# Output the body:
my @parts = $entity->parts;
if (@parts) { # multipart...
my $i;
foreach $i (0 .. $#parts) { # dump each part...
dump_entity($parts[$i], ("$name, part ".(1+$i)));
}
}
else { # single part...
# Get MIME type, and display accordingly...
my $type = $entity->head->mime_type;
my $body = $entity->bodyhandle;
if ($type =~ /text\/html/) {
if ($IO = $body->open("r")) {
while (defined($_ = $IO->getline)) {
push @mailText, $_;
}
$IO->close;
}
else { # d'oh!
print "$0: couldn't find/open '$name': $!";
}
} elsif ($type =~ /text\/plain/) {
push @mailText, "
";
if ($IO = $body->open("r")) {
while (defined($_ = $IO->getline)) {
push @mailText, $_;
}
push @mailText, "";
$IO->close;
}
else { # d'oh!
print "$0: couldn't find/open '$name': $!";
}
} else { # binary: just summarize it...
my $path = $body->path;
my $size = ($path ? (-s $path) : '???');
$f = basename($path);
push @mailBody, "Attached $f Size:: $size bytes
";
}
}
1;
}
$id = $q->param('id');
$stmt = "select envip,mailfile,headers,subject,size,fromid,toid,date from quamail where id = $id";
@row = $db->selectrow_array($stmt);
($envip,$mailfile, $headers, $sub, $size, $from , $to, $date) = @row;
push @mailBody, "From: $from
";
push @mailBody, "To: $to
";
push @mailBody, "Date: $date
";
push @mailBody, "Subject: $sub
";
push @mailBody, "
";
$mfile = "/quamail/$mailfile";
$parser = MIME::Parser->new;
$parser->output_under("/tmp");
$entity = $parser->parse_open($mfile);
push @mailBody, "
";
&dump_entity($entity);
push @mailBody, "
";
push @mailBody, @mailText;
$h = {'mailBody' => [@mailBody]};
print($json->pretty->encode($h));
@delfiles=;
$ign = rmtree(@delfiles, {verbose => 0});
IP geolocation query
Here is an IP geolocation lookup done in Perl.
#!/usr/bin/perl
use File::Basename;
use lib dirname (__FILE__);
use SpamCheetahDBQuery;
use IO::Socket;
use JSON;
use CGI;
use Sys::Syslog;
$q = CGI->new;
$| = 1;
openlog("GeoIP Countrywise");
print $q->header('application/json');
$ipsock = "/tmp/ipsock";
@ips = SpamCheetahDBQuery::dbQuery("geoip");
%cntryHash = (), %h = ();
for $ip (@ips) {
$cntryHash{$ip} += 1;
}
sub queryapi {
($ip) = @_;
my $ipjson = IO::Socket::UNIX->new(
Type => SOCK_STREAM,
Peer => $ipsock);
print $ipjson $ip . "\n";
my $info = decode_json(<$ipjson>);
$cntry = $info->{'countryCode'};
$cntryName = $info->{'country'};
$h{$ip} = "$cntry,$cntryName";
syslog("info", "Country code $cntry");
}
for $ip (keys %cntryHash) {
&queryapi($ip);
}
%outh = ();
%tmph = ();
for $ip (keys(%cntryHash)) {
($cntry, $name) = split /,/, $h{$ip};
$h{$cntry} += $cntryHash{$ip};
$outh{$cntry} = { 'value' => $h{$cntry} };
$tmph{$name} = "$cntry,$h{$cntry}";
}
@table = ();
for $name (keys(%tmph)) {
($code, $val) = split /,/, $tmph{$name};
push @table, {"country" => $name,
"code" => lc($code),
"mails" => $val};
}
my @table = sort { $b->{'mails'} <=> $a->{'mails'} } @table;
if($#table gt 9) {
@table = @table[0..9];
}
$json = JSON->new;
if ($q->param('table')) {
print($json->canonical->pretty->encode(\@table));
} else {
print($json->canonical->pretty->encode(\%outh));
}
In the above example, you find Perl uses hashes to good effect. It
usually takes some years of getting to know Perl to be able to code
idiomatically and effectively.
Perl daemon example
Here is daemon code I use as well.
#!/usr/bin/perl
use Tie::File;
use Sys::Syslog;
use JSON;
use Proc::Daemon;
use Proc::PID::File;
use IO::Socket::INET;
sub refresh_mtaip {
local $/;
# XXX read spamcheetah config and store vals
open F, "/etc/spamcheetah.json";
$conf = ;
close(F);
$json = JSON->new;
$dec = $json->decode($conf);
%schash = %$dec;
$/ = "\n";
$mtaip = $schash{'mtaip'};
}
openlog("Activate_mta");
sub resume_relay {
syslog("info", "MTA is up resuming relay");
tie @conf, "Tie::File", "/etc/pf.conf";
for (@conf) {
chomp();
next if(/^#/);
if(/rdr-to 127\.0\.0\.1 port 6300/) {
last;
}
if(/port smtp\s*$/) {
$_ =~ s/\s+$//;
$_ .= ' rdr-to 127.0.0.1 port 6300';
}
}
untie @conf;
system("/sbin/pfctl -f /etc/pf.conf");
system("/usr/bin/pkill -HUP smtprelay");
syslog("info", "Nothing to do EXIT");
exit(0);
}
sub pass_thro {
tie @conf, "Tie::File", "/etc/pf.conf";
for (@conf) {
chomp();
next if(/^#/);
if(/rdr-to 127\.0\.0\.1 port 6300/) {
$_ =~ s/$&//;
}
}
untie @conf;
system("/sbin/pfctl -f /etc/pf.conf");
syslog("info", "ACTIVATED pass thro' as MTA $mta is down");
}
sub check_mta {
my $sock = new IO::Socket::INET (
PeerAddr => $mtaip,
PeerPort => '25',
Proto => 'tcp',
Timeout => 15
);
if($sock) {
&resume_relay;
}
}
&pass_thro;
Proc::Daemon::Init();
die "Already running!" if Proc::PID::File->running();
for(;;) {
syslog("info", "Running in pass thro' mode");
syslog("info", "Sleeping 2 minutes");
sleep(120);
&refresh_mtaip;
$res = &check_mta;
}
As you can see from above examples, I am heavily invested in Perl.
And if you can write daemons and background server processes, then
that is definitely not scripting or automation.
That is serious stuff.
Perl CGI
In the world of server-side processing, before the ubiquity of
JavaScript and the advent of HTML5 (and before the browser itself
becoming so heavy in functionality and features), nobody could use a
website without Perl CGI for database queries and backend work.
But Perl and CGI both seem to be less talked about in the web
context. Now servers for HTTP are run in node.js, be it on the
frameworks Express, Hapi, or Koa.
Still for most web applications, Perl continues to shine in CGI. The
CGI scripts that do important database queries can be easily
performed and wrapped into a Perl script that follows rules of CGI.
Here are some sample scripts that use various OS-level inter-process
mechanisms like UNIX domain socket.
e JSON;
use CGI;
use DBI;
use IO::Socket;
use Sys::Syslog;
use JSON;
$q = CGI->new;
print $q->header('application/json');
openlog("Dashboard");
$json = JSON->new;
my $proxysock = "/tmp/proxysock";
my $db = DBI->connect("dbi:Pg:host=/tmp", "postgres", undef, {AutoCommit
=> 1});
if(!defined($db)) {
print("error","Could not connect to Postgres db");
}
sub getstats {
my $proxy = IO::Socket::UNIX->new(
Type => SOCK_STREAM,
Peer => $proxysock);
print $proxy "DUMPSTATS";
@out = <$proxy>;
for(@out) {
chomp;
($parm,$n) = split/=/;
if ($parm eq "totalmailattemptcnt") {
$outh{"mails"}= $n;
} elsif ($parm eq "goodmailcnt") {
$outh{"goodmail"} = $n;
} elsif ($parm eq "numattcnt") {
$outh{"numatt"} =$n;
} elsif ($parm eq "regexcnt") {
$outh{"regmatch"} =$n;
} elsif ($parm eq "viruscnt") {
$outh{"viruses"} = $n;
} elsif ($parm eq "spamcnt") {
$outh{"spamcnt"} = $n;
} elsif ($parm eq "relaydeniedcnt") {
$outh{"relaydenied"} = $n;
} elsif ($parm eq "bannedrecipcnt") {
$outh{"badrecip"} =$n;
} elsif ($parm eq "bannedsendercnt") {
$outh{"badsender"} = $n;
} elsif ($parm eq "blockedmimecnt") {
$outh{"badatt"} = $n;
} elsif ($parm eq "rfcrejcnt") {
$outh{"rfcrej"} = $n;
} elsif ($parm eq "fqdnrejcnt") {
$outh{"fqdnrej"} = $n;
} elsif ($parm eq "dkimrejcnt") {
$outh{"dkimrej"} = $n;
} elsif ($parm eq "spfrejcnt") {
$outh{"spfrej"} = $n;
} elsif ($parm eq "helorejcnt") {
$outh{"helorej"} = $n;
} elsif ($parm eq "mailszcnt") {
$outh{"mailszrej"} = $n;
} elsif ($parm eq "rblrejcnt") {
$outh{"rblrej"} = $n;
} elsif ($parm eq "score") {
$outh{"score"} = $n;
} elsif ($parm eq "sender_nomx") {
$outh{"sender_nomx"} = $n;
} elsif ($parm eq "norevdns") {
$outh{"norevdns"} = $n;
} elsif ($parm eq "malware_attach") {
$outh{"malware_attach"} = $n;
} elsif ($parm eq "malware_url") {
$outh{"malware_url"} = $n;
}
}
}
sub query_mails {
$stmt = $db->prepare("select count(*) from mails;");
($mail_count) = $db->selectrow_array($stmt);
}
sub query_quarantine {
$stmt = $db->prepare("select count(*) from quamail;");
($qua_count) = $db->selectrow_array($stmt);
}
# XXX execution start
%outh = ();
&getstats;
&query_mails;
&query_quarantine;
$outh{"Mails"} = $mail_count;
$outh{"Quarantined"} = $qua_count;
syslog("info", $json->canonical->pretty->encode(\%outh));
print($json->canonical->pretty->encode(\%outh));
$db->disconnect;
Without server side processing nothing moves.
Tags: perl, unix
Podcast logo The Stack Overflow Podcast is a weekly conversation
about working in software development, learning to code, and the art
and culture of computer programming.
Related
[se-10-year] community June 27, 2022
Celebrating the Stack Exchange sites that turned ten years old in
Spring 2022
From Chemistry to Raspberry Pi: Sites covering Q&A on tech, leisure,
language, and more celebrate their first decade.
Avatar for Rosie
Avatar for Ryan Donovan
Rosie and Ryan Donovan
[230522-Stack-Overflow-The-Science-of-Interviewing-Developers-1200x630]
code-for-a-living May 23, 2022
The science of interviewing developers
All those CEOs on LinkedIn claiming they can find the right candidate
in a five-minute conversation? Wrong. Science shows us how we can do
better.
Avatar for
Isaac Lyman
[010422-Stack-Overflow-Read-to-go-1200x630] code-for-a-living April
4, 2022
Comparing Go vs. C in embedded applications
Impossibly tight deadlines, unrealistic schedules, and constant
pressure to develop and release applications on time, while at the
same time achieving excellent quality. Sound familiar?
Avatar for
Marcin Pasinski
[0322-Stack-Overflow-Black-Box-Testing-1-1200x630] code-for-a-living
March 9, 2022
Rewriting Bash scripts in Go using black box testing
When rewriting software in a new language, how do you test that your
new and old programs do the same thing?
Avatar for
Daniel Orner
36 Comments
[1cd] TylerH says:
6 Jul 22 at 11:36
"but has undergone many changes since then (even spawning another
programming language, Raku)."
Isn't Raku just a renaming of Perl starting at version 6.0 of the
language? That's how it is described, anyway.
Reply
* [e68] Ryan Donovan says:
6 Jul 22 at 12:01
Raku was Perl 6, but they are considered separate, independently
evolving languages. From https://www.perl.org/about.html
""Perl" is a family of languages, "Raku" (formerly known as "Perl
6") is part of the family, but it is a separate language which
has its own development team. Its existence has no significant
impact on the continuing development of "Perl"."
Reply
+ [1cd] TylerH says:
6 Jul 22 at 3:37
Hmm, it sounds like Perl doesn't know what it is then. From
the paragraph directly before the one you quoted, it says
"Perl is a highly capable, feature-rich programming
language". So it's... a single programming language, *and* a
family of languages all at once. And the folks here at SO
(ostensibly the experts, I hope!) felt Perl 6 (otherwise
known as the latest version of Perl) is renamed now to Raku,
and that there is no more Perl moving forward (e.g. Perl
refers to versions 5.x and older only), but the Perl 5.x-ers
seem to not like that idea? Talk about a family feud!
Reply
o [acd] Dave Cross says:
7 Jul 22 at 11:50
Perl 6 was announced in 2000 as the next version of Perl.
At some point around 8-10 years later, when it still
hadn't been released, the relationship between Perl 5 and
Perl 6 was redefined to make them two different members
of a family of programming languages.
This split was emphasised in 2019 with the renaming of
Perl 6 to Raku.
Perl 5 is still in active development (although you
wouldn't believe that from the 20-year-old code in this
article) and there have been conversations about what
might, at some point in the future. become Perl 7.
Raku is also still actively developed but, as far as I
can see, it has been struggling to get the traction it
needs to be taken seriously in the industry.
Perl knows what it is. Raku knows what it is. Together
they make up the Perl family of programming languages.
There is no family feud here.
Reply
* [65a] Bob says:
7 Jul 22 at 3:49
Some random thoughts:
Re: shell scripts:
The temptation to do a 4 line shell script to abbreviate some
frequently done task is large. But anything more than a few
lines, I do in Perl instead. Once you have to parse input
parameters or do almost anything other than a quick pipe, it's
easier and IMO, *more readable*, to use Perl w/ system() commands
or " to get output into variables for further processing and
feeding into further commands.
I don't remember the last time I saw an OS that used bash, ksh,
etc and didn't also preinstall Perl 5. I'm sure there are some, I
just haven't encountered them.
Python is good, I use it now. It's a bit painful, but it's
throwing of exceptions in cases where where perl might just give
you a warning (that may get hidden in a log file) forces one to
fix problems *now*. This is less of an issue if one religiously
checks the return values of system calls, for example, but hey,
I'm human.
There's no excuse for the lack of "use strict; use warnings" in
example code.
One thing I *really* miss in Python is lexical scoping in blocks,
and being able to make blocks *anywhere*. Doing *everything*
possible in functions, including main() , helps with this.
On the other hand, the "batteries included" philosophy of
Python's standard libraries is pretty cool. itertools and
functools has a lot of cool stuff.
lambda is weak as hell compared to
{ do anything here }
Reply
[9e1] Darrin M. Gorski says:
6 Jul 22 at 2:31
Good article, always good to hear there are others like me out there.
"When it comes to the performance of node.js and its event loop
single-threaded performance, Perl is not a contender."
I'm not sure I agree here - see EV and Mojolicious for some really
good examples of Perl doing this just as well. You can write async
perl just as easily as javascript. If that's what you want.
"In the race for performance and modern trends, Perl definitely
appears a bit dated. But it does have a place as we have seen above."
Actually, I think the reason Perl still exists and that people still
use it is because it is perfectly capable of keeping up with modern
trends. Perl code I write today is not the same as that which I wrote
20 years ago. I'm pretty sure other languanges have influenced the
way I write perl and I expact that to continue to be the case.
- Darrin
Reply
[8ae] JimmyK says:
6 Jul 22 at 2:55
You've convinced me to switch to Python.
Reply
[c2f] Blaine Motsinger says:
6 Jul 22 at 8:46
CGI for web application development in Perl is very outdated. Please
see Dancer2 and Mojolicious for modern examples of web application
frameworks in Perl, similar to Express in node.js.
Reply
* [f6d] Steve says:
7 Jul 22 at 4:07
I have experience with using Perl for CGI and Dancer2.... there is
absolutely -NO- reason everything has to be done in Dancer or
Mojo. In a lot of cases, Dancer is a huge overkill that is pushed
on people to use just because its "the modern way".
Each method and tool chain have their own strengths and
weaknesses. CGI works for some tasks, Dancer works for other
tasks. Use the right tool for the right job.
Reply
[fb1] Lebbeous says:
6 Jul 22 at 11:40
Nice article. Even though I more often reach for Python nowadays, I
still have a fondness for Perl and will sometimes use it, especially
if what I need to do is centered on applying regular expressions or
using UNIX pipes.
I have a quibble: when you describe CPAN modules that offer both
object-oriented and "functional" interfaces (and when you give your
sha256 example), you mean procedural, not functional. However, when
you later mention functional programming concepts in Python like
lambda and map, that usage of "functional" is correct.
Reply
[451] Aman says:
7 Jul 22 at 1:26
Can you share any resources link to learn Perl?
Reply
* [acd] Dave Cross says:
7 Jul 22 at 11:51
https://learn.perl.org/ would be a good place to start.
Reply
[dbb] leejo says:
7 Jul 22 at 3:00
It's frustrating to see this low quality article posted to
stackoverflow. It posses a legitimate question then fails to answer
it in a compelling way, using 20 year old poor quality Perl code in
all the examples.
This is yet another example of a mediocre Perl developer that is
either not beyond the surface in their knowledge or hasn't kept up
with the language for, oh, at least 15 years. Almost every sentence
in the post contains either bad or out of date information. The
author should feel bad.
Reply
[77e] George M Jempty says:
7 Jul 22 at 3:21
"People talk of node.js streams and so on, but to me it looks like a
joke..." This and other statements about node.js make this article seem
like FUD to me
Reply
[acd] Dave Cross says:
7 Jul 22 at 3:40
It's great to see Stack Overflow publishing a positive Perl article
like this. But it would be even better if it was written by someone
whose knowledge of Perl wasn't about twenty years out of date.
A lot of the code here looks really dated.
* No "use strict" or "use warnings"
* No declaration of variables
* Using '&' to call subroutines randomly - it's not needed in any of
these examples
* Using CGI for web programming
* At least one example of "new Class" instead of the recommended
Class->new()
* Using bareword (global) filehandles instead of lexical variables
* Two-argument version of "open()" instead of the, safer,
three-argument version
Perl is a powerful, modern language. But you wouldn't believe it from
reading this article.
Reply
* [e7e] arslonga says:
8 Jul 22 at 4:27
Correct point about the CGI.
What Perl lacks are ready-to-use programs that beginners could
familiarize themselves with.
I tried to create something in the field of web programming. This
is my CMS for a site on Mojolicious. Unfortunately, the code
doesn't look perfect because my knowledge of Perl is not
systematic enough.
The link to my MornCat CMS: https://github.com/arslonga/my_blog
Reply
[200] Mike Nakis says:
7 Jul 22 at 4:20
How about "Why Perl _is not_ and has _not_ been relevant for the past
couple of decades" ?
And how about "Why no weakly typed language ever was relevant, for
anything" ?
Reply
* [55a] Erik says:
7 Jul 22 at 3:42
uhm, just because it's not the case, that's why
Reply
[6d7] Hayden says:
7 Jul 22 at 5:11
But the libraries are rotting.
Installing any significant library installs huge dependencies, with
0.0.1 version numbers.
Plus many of us will recognise Perl as a write-only language, in that
if you don't use if for a week or two, you're back to re-learning
what the line-noise means.
Reply
[a57] Darius says:
7 Jul 22 at 5:29
The code snippets of the "Bonus: Perl code you can use" section are
pretty low quality. Just to point out a few issues:
- missing `use strict; use warnings;`
- `my $i; foreach $i ...` instead of `foreach my $i ...`
- useless initialization of arrays and hashes (eg, `@mailBody =();`)
- some variables declared earlier than necessary (eg, `my $IO;`)
- just a print instead of a die/exit after `if (!defined($db))`
- global instead of lexical filehandles
- use of `gt` instead of `>` for number comparison
- functions called with `&f` instead of simply `f()`
- useless hash copy in `%schash = %$dec;`
- ...
In fact, this kind of Perl code is exactly the reason why people
don't like Perl: it's messy, errors are poorly handled, it's hard to
understand, the lack of strict/warnings means that things will break
at execution time rather than at compile time...
Reply
[f5f] Stefano Borini says:
7 Jul 22 at 7:40
Perl is only relevant as an example of what NOT to do when designing
a language.
Reply
* [77e] George Jempty says:
7 Jul 22 at 8:29
Will Hunting: "You got that from Matz....do you have any thoughts
of your own?"
Reply
[d55] Martin says:
7 Jul 22 at 8:26
Pretty much all of Perl's "pros" listed here are also present in
Python, and a myriad other scripting languages. Funny how you glossed
over Perl's biggest "con", which is that it's absolutely unreadable.
As to your "Why it's still relevant" points, those same arguments
could be made about COBOL. Ancient Perl scripts are still up and
running, yes, precisely because they're so critical and
undecipherable that nobody will dare to touch them. I never really
see any new exciting projects being started in Perl.
Reply
* [77e] George M Jempty says:
7 Jul 22 at 11:11
I am not pro-Perl by any means but the "Perl is unreadable" trope
was invalidated for me over two decades ago doing my first
professional Perl programming (I'd learn it for CGI on the side)
and, it seemed perfectly readable at the time, and still does
those two decades hence.
Reply
+ [f6d] Steve says:
7 Jul 22 at 4:12
Yeah, people like to parrot that crap line about Perl every
chance they get. It gets old.
I've seen really clean and easy to read Perl code, and I've
seen crappy looking Javascript and Python.
Reply
* [a31] e. alvarez says:
7 Jul 22 at 8:45
Much of the Nix tooling is written in Perl.
Try again.
Reply
[120] Pluto says:
7 Jul 22 at 10:34
Seems pretty similar to PowerShell, but less readable and less
powerful. PowerShell integrates with operating system commands and
fully supports piping and so on, but it also has .NET CLR code to
fall back on if any additional functionality is useful AND is already
installed in the operating system. It may not be as powerful in the
CGI world, but who wants to use a scripting language when building a
web server anyways?
Reply
[8c4] L.G. says:
7 Jul 22 at 1:27
I disagree that Perl, in and of itself, is difficult to read. Any
language can be written so poorly as to render it's code unreadable
at first glance. I recognize the deficiencies of this language and
can understand why its popularity has declined over the last decade
(or more). And perhaps this article is a bit rosey in its treatment
of Perl. Yet the language is still used. New code is still written in
Perl, just as new code is still written in FORTRAN. (Now there's an
old language.) I may be partial to coding in Perl compared to Python,
but we can do most anything in either language. I simply prefer to do
it in Perl.
Reply
* [725] qwr says:
7 Jul 22 at 11:30
FORTRAN has over half a century of scientific computing libraries
and legacy behind it.
Reply
[725] qwr says:
7 Jul 22 at 3:43
Why does your code look like it was written in the 2000s
Reply
* [acd] Dave Cross says:
8 Jul 22 at 5:45
Looks like he hasn't kept up with the last twenty or so years of
Perl development.
Reply
[49e] Xiong Chiamiov says:
7 Jul 22 at 6:42
Among other problems, the biggest issue with this article is that it
doesn't even mention Ruby as a competitor. Any situation where Perl
would be a better choice than Python, Ruby fills that niche even
better IMO, as a language that took Perl's text munging and combined
it with Smalltalk's OO model (and got rid of Perl's notable warts
like sigils and implicit args).
Perl is probably a good choice for you because you're familiar with
it, but that's a different question than what language is good for
someone else to pick up.
Reply
[bcf] simbabque says:
8 Jul 22 at 4:52
It's nice to see that Stack Overflow is willing to publish something
positive about Perl, and I'm grateful to the author for taking the
time to write it, but I am sad about the lack of quality in this
article. It makes me wonder where the quality control has gone. I
expect to read articles that are much better edited on an official
blog by a company such as Stack Overflow.
Others have already pointed out what's bad about this article, so I
would like to focus on the community around Perl on Stack Overflow.
There are not many new questions in the Perl tag compared to other
languages. At the moment, we get something like 5 a day on average,
with the weekends being quiet. Almost all of them get answered, and
most of them get accepted. A lot of questions are fairly entry level,
and often by new users. It's common that a new user will ask a series
of questions to figure out a given problem, and the quality of their
questions often improves significantly while doing this.
Then there are users who have been around for many years, and every
so often they ask a question that takes a little bit of research to
answer. It's always nice to see one of these, because it reminds me
that there are more professionals out there going about their jobs,
and that they come and seek the experience of other like-minded
people, just like me.
Finally, we have the group of regulars, the experts who answer most
of the questions, often within a few hours. There are probably about
5 very active ones of us at the moment, and about 10 in total. Many
have been active on Stack Overflow for a good 10 years, but some are
much newer. We count a few 100k users among us, and there are CPAN
maintainers, published authors of Perl books and even a few regular
contributors to the Perl 5 core itself.
If you have a Perl problem, you will usually get an answer here. It
will be professional, constructive, concise and modern, often
pointing out further improvements to the code in the question. I
think I'm not alone when I say we do this because we enjoy Perl and
we enjoy helping people get better at it.
It would be nice to see all of this expertise be called upon before
something gets published under the official Stack Overflow banner.
It also would be mean to assume anything but good faith, so i'd like
to extend to the author an invitation to help him learn more about
modern Perl. A lot has happened in the last 20 years that you haven't
seen yet, I believe. Get in touch, and we'll show you.
Reply
* [e68] Ryan Donovan says:
8 Jul 22 at 10:55
I rely on pitches from external writers for articles like this.
If you would like to improve the quality of articles by pitching
one of your own, please email me at pitches@stackoverflow.com.
Reply
+ [148] smonff says:
8 Jul 22 at 1:58
We started a community review of the article so that Girish
could provide a second version of the post.
Reply
[845] TJ says:
8 Jul 22 at 4:27
I'll admit that I've been spoiled by modern, easy-to-read programming
languages, but I did try Perl and found it unutterably unreadable and
after endless weeks cutting my teeth decided to go back to my cushy
life writing x86 assembly grateful I don't have to work with such
unreadable line-noise every day.
Reply
Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked
*
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
Comment * [ ]
Name * [ ]
Email * [ ]
Website [ ]
[ ] Save my name, email, and website in this browser for the next
time I comment.
[Post Comment]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
D[ ]
This site uses Akismet to reduce spam. Learn how your comment data is
processed.
(c) 2022 All Rights Reserved.
Proudly powered by WordPress
Stack Overflow
About Press Work Here Contact Us Questions
Products
Teams Advertising Collectives Talent
Policies
Legal Privacy Policy Terms of Service Cookie Settings Cookie Policy
Channels
Blog Podcast Newsletter Twitter LinkedIn Instagram
*