The joy of Perl
salon.com
salon.com
I suppose Carrol and Tolstoy are to be quoted when asking a natural language guy about computer languages.... ;-)
Honestly, for the last 6 years I have been doing mostly Perl programming (and managing an open source project largely written in Perl) and if I can't easily read a contribution easily I push back.... Perl doesn't have to be hard to read. I would say, however, that keeping things minimalistic is a real virtue in the language.
Ready for this?
The way I see, Any other way of doing regular expressions sucks more badly. In fact if you are look to replace your regular expressions with something else you are likely to inherit a thick verbose pile of junk. Now why do regular expressions work.
Look at this thing below:
$line =~ m/<some regex>/;
This can also be written as, $line =~ m'<some regex>';
or $line =~ /<some regex>/;
This matches the line with <some regex>, Why is this special? Because it just allowed to you match a line without first compiling the regex, and then matching it. Not just that it saved you from writing several tens of lines of code before using a regex which you generally have to do in other languages. So you can do something like: if ($line =~ /regex/)
{
}
or do_something() if $line =~ /regex/;
This is a bit of natural language way..In case of file operations:
while(<FILE>)
{
chomp;
#Do your stuff
}
There are some amazing things that Perl does like my @file_content = `cat somefile`;
Suddenly all contents are in an array in your program.Worried about removing new lines from that array? Just do
chomp(@file_content)
Want to go over that file now? Just do foreach my $line(@file_content)
{
#Do your stuff here
}
Want to deal with that line? You have, my @fields = split( /<some regex>/, $line );
Want to do more matching/extracting from lines? my @processing = map { do_something($_) } @fields;
Want to find something in that array? my @results = grep { /some regex/ } @fields;
Want to handle exceptions? eval
{
#Some operation
}
if $@
{
#Handle exception
}
open( FILEHANDLE , '<' , $file ) or die "Cannot open file";
Just felt the need to create a small database? use strict;
use warnings;
use DB_File;
use Fcntl;
my %some_hash
tie (%some_hash, "DB_File", $dbm_file, O_RDONLY or die "Unable to open dbm file $dbm_file: $!";
#change your hash
untie(%some_hash);
You just got a key-value database.Want to execute a shell command?
`/some/command/execute`;
or system('/some/commmand/execute');
Need to create a function? sub function_name
{
my ($var1,$var2..) = @_;
}
Need to create a Class or a Package? package Name;
#do stuff here
1;
You can also create anonymous functions my $function = sub {};
$function->();
This also means you can create a closure: sub function1
{
my $function = sub {#does something};
return \$function;
}
In latest versions of Perl, there are some cool features like: given($some_data_structure) #what ever that is array, reference etc
{
when ( #some match operation ) { #do something }
...
...
}
this serves both as a smart matching loop/switch statment.All the above gives you quick scripting tools.
You also have your usual set of ternary operator,if..else, you can also quote regular expressions.
Now why did I write this, I wrote this to tell that. Perl's motto is to get stuff done. In a no BS way. It adapts to your style, its Object oriented, its functional etc. You decide the style the language bends to you.
You get Best of the OO features from Moose(http://search.cpan.org/~doy/Moose-2.0402/lib/Moose.pm), You get modules like Devel::Declare and DBIx::Class, You also get a framework like catalyst. At the same time you can write in funtional programming techniques. You can do cool stuff like Memoization and higher order parsing. For more information read Mark Jason Dominus's Higher order Perl - (free ebook) http://hop.perl.plover.com/
At the same time you as a novice can begin with programming with what you understand Read Chromatic's Modern Perl Book - (free ebook) - http://onyxneon.com/books/modern_perl/
You can do Object oriented programming, Functional programming, Declarative programming all without shoe horning things using frameworks. You can build big to medium sized apps. Its difficult to demonstrate all that in a post, Hence read MJD's book.
But at the very same time you can use it as a scripting language in which you can cook scripts are at a very quick pace, You can quickly prototype, solve data/text processing problems. You can make it behave like awk, sed and what not. You can create quick databases.
No wonder its still among the top programming languages in the world even after 25 years since its release.
Last but not the least, Its killer app : http://www.cpan.org/
sub function_name
{
my ($var1,$var2..) = @_;
}
I know why methods are like that, but it doesn't make me any less unhappy to have to read a function in order to figure out what types and what order I need to pass values to a function.There's a few Perl programmers at work who end up using just a bunch of global variables instead of doing pass by reference or returning values from subs.
sub do_something { # modify %my_global_hash }
It's just strange working with Perl after working in more OO languages. But, like you said, Perl adapts to your style. I want it more like other languages I've written in, whereas the people I work with don't.
Getopts::Long is amazing for parsing command line, and I don't know how I would work without being able to do the inline if and unless statements.
There are other modules out there like this, including one that bakes it into Moose methods. This also highlights a cool Perl feature: hack able syntax.
https://metacpan.org/module/Method::Signatures https://metacpan.org/module/MooseX::Method::Signatures https://metacpan.org/module/Method::Signatures::Simple
and many more. In this case, there might be too many ways to do it.
While writing Perl one liners it might become difficult to fit in the parameters in the usual C based function implementation syntax, in such cases this might turn out useful.
Let us not forget sysadmins use Perl a lot on the command line.
Once you realize that the control structures flow like an English sentence, once you grok that, the language simply gets out of the way. It's not bound to an ivory tower of a certain paradigm. It's a human language. Sure you can write Perl that's almost unreadable, but you can do that in many programming languages, and you can do it in real human languages. Written well, reading Perl is like reading beautiful poetry.
Case in point, I once wrote a program in Perl, about 30,000 lines of code (which by Perl standards is relatively large, a Java port ended up about six times as large), then didn't see it for 2 years. I was asked to guide a team to port the code to Java, I sat down one afternoon, and just read the code like a book. After that I almost never had to refer to the code again, and guided the team through the rest of the porting process. I knew it like I had just read a novel. Cause and effect was obvious, the bundling of the chapters (modules) made dramatic sense, and when I had to refer to the code to show it to one of the Java devs, it took seconds to find the code segment in notepad of all things.
Very little boilerplate, the best integration of regexes in the industry, yet still powerful enough to write major sites and applications in.
Downside: it ruined me as a developer, all the BS you have to go through in other languages to just get something done seems like such busy work. I ended up writing a set of libraries in C++ to handle lots of things in a perlish sort of way, typeless primitives, perl style containers, etc. But at the time C++ didn't have the same kinds of sentence-like control structures and simple regex matches always became a dozen lines of compiling regexes and then matching, and then iterating some data structure to get at the results. Painful.
Java became intolerable. I remember the last time I sat down to write something in Java, spending hours hunting through the standard library documentation thinking "this is bullshit, I shouldn't have to create xyz minor feature from whole cloth, it's got to be in the standard library, for fuck's sake Java has 3 gui frameworks and I have to parse a csv file by hand!!!"
According to Ohloh, LedgerSMB has 54k lines of Perl code. The quality of code ranges from abysmal (mostly inherited code from SQL-Ledger, things like some_func(\%config_has, \%$object)... \%$object? wtf?) to code that I am actually thinking is starting to look very elegant, even if it isn't a popular way of doing some things.
I find for me the boilerplate is all POD suff. Very little boilerplate in code.
I think a big downside though is that some developers are uncomfortable with the flexibility. They want to do Perl the Python way, or the Ruby way. This leads to code that's hard to follow very fast....
I came to the Perl party a pretty late. But Perl is so much like Emacs. Once you learn it well the productivity gains are exponential.
Once you are familiar with the language to a level. The program just flows out naturally even as your thinking. And yes to mention somethings in Perl make it so easy for that happen is really Larry's genius to build such a thing.
This is also what enables a person to write useful applications in very little time, while avoiding most of the cruft traditional languages have.
The surprising thing is, most people don't know about this. But when they first encounter it literally hits you like a lifelong addiction.
I do a lot of innovation at $dayjob and most of the times people think I'm a genius or super productive. But, its only that Perl enables me to do stuff so quickly it often looks like magic to people around.
If you're coming back to perl, read Modern Perl. Then learn Moose and its ecosystem. That will get you about 90% of the way to writing good, maintainable perl. :)
some systems, such as human and computer languages, contain a minimum amount of complexity, and that attempting to "push down" the complexity of such a system in one place will invariably cause complexity to "pop up" elsewhere.
Take for example the given-when syntax in Perl - http://perldoc.perl.org/functions/given.html
It really works hard enough to work as a switch statement with smart matching - http://perldoc.perl.org/perlsyn.html#Switch-statements with the adapting to the user intention.
I have always wondered how the Perl will evolve in the future. I see it will look more and more like Perl 6 adding features to make the magic look spectacular and amazing. We are already seeing Moose and Moosex and various other modules developed using Devel::Declare and the amazing stuff that they can do.
By working to match the user intention, the programmer generally can build the program in his head even while he is imagining the features.
Overall the greatest power of Perl that I have seen is, You can start your text editor and really build things as you think. Unlike many languages where you need a IDE which 100's of MB's heavy or you have to continually bother dealing with piles and piles of verbose code which often requires hours and hours of effort figure out what's happening underneath the layers.
I just wrote it as things were flowing out of my mind.
There are likely to be mistakes.
And after all, its a comment.
I wonder if the difference in book sales is at least partly an artifact of the relative difficulty to learn Perl compared to Python.
That's a hell of a caveat. :) As I get older, I find I spend more time reading code than writing it (even though most of it's my own), and I find Python's sheer readability indispensable.
And if you have good programmers, then readability isn't a problem. Not even a thing to think about.
Hrm, I'd argue against that.
I know better programmers than me, whose code I hate to work with. Also for Python.
But you seem to define "good programmer" as someone who also comments and documents, so I guess you're by definition correct. :-)
Edit: Yeah, "itsnotme". The fault is rather the idiot bosses that let the smart idiots get away with it... But with non-idiot bosses, you won't have readability problems in Perl either.
Those who write too few comments.
Those who write too many comments.
Those who write the wrong comments.
Of course, those are not mutually exclusive.......
Like some one mentioned in this thread, languages tend to be judged by the quality of code produced by their worst user.
For once you can write unreadable code in any language. Even in C and Lisp. In fact there you can create bigger problems and more unreadable code.
(And in scripting languages which doesn't declare parameters, like Python and old style Perl, you need to document what the parameters are.)
What I used to say, which probably other people do too, is "Perl is a best language to write programs in so long as you can fit it in one line of code!"
Edit: I don't mean that as a criticism of Python. I use it daily and like it. It's just that Perl was more fun. That's all I mean to say.
The way we are moving towards things in LedgerSMB is:
Web and file format (csv, latex, etc) templates in TemplateToolkit
Everything that can be done as set operations in the db in the process of storing/retrieving info is done in PL/PGSQL.
A brief framework written in Perl
And the rest of the Perl code essentially is written to be very light-weight automation glue between these layers.
"Wall has Caller ID hooked up to his computer, which he has instructed to emit unique sounds for each incoming call. What good is Caller ID, asks Wall, if you have to walk all the way over to the telephone to see who is calling?"
I have had others praise code I have just whipped up.
However, the trick here is to get used to documenting your code as you write it. That avoids most problems. It also forces you to clarify your thoughts as you write the code. Clear thought becomes readable code. Messy thoughts become a nightmare.
But, considering CPAN and Moose, you get much less code in Perl to read, for quite a lot of use cases. If that is not important to you, use C...
The other nice story carried on HN was how Linux Torvalds was remembered by the Red Hat folks with a nice payback in shares as a thank you for everything he did.
The internet really helps too, allowing a dollar here and a dollar there to really add up when genuinely appreciative people make voluntary donations. Bram Cohen is a good example here, who receives well deserved donations from all the folks who love bittorrent.
I believe this model of giving (and the return karma) augurs well for society. There is room for a lot of hope and optimism.