Sunday, March 7, 2021

php was such a nice step over perl

I get a little defensive over my use of PHP (and keep a link Taking PHP Seriously handy) - I sometimes wish my rented server had more options for doing serverside stuff in javascript, say, but PHP is both convenient and performant.

My server-based blog/diary/database still uses a lot of legacy Perl CGI - if it ain't broken why fix it? - but lately it HAS been breaking, logs showing "Cannot allocate memory: couldn't create child process" errors. So I figured it was time to update things to PHP and get rid of the CGI dependency. 

(I still owe a debt to Perl - see what perl taught me (in the early-mid-90s))

One thing about PHP - it's such a mature environment, in terms of almost every utility you'd want is baked into the language - no CPAN or npm hell or hacking up some regex, it's just there. Case in point, here's a legacy Perl function for my private diary (a bunch of flat files, one per day) I'm porting now

sub dateGoneOrEmpty{
    if(! (-e "entries/$justwhen.txt")){
	return 1;
    }
    open(READ,"< entries/$justwhen.txt");
    my $buf = "";
    while(defined($line=<READ>)){
	$buf .= $line;
    }
    close READ;

    if($buf =~ /MORE/){
        return 1;
    }

    if($buf =~ /\S/){
	return 0;
    }
    return 1;
}

The "$justwhen" is a datestamp used as filename... this function returns 1 if the file doesn't exist, is empty, or just has the word (all caps) MORE in it (an old hack I used when I knew I wanted to come back and put in more details in a day's entry)

But the syntax is kind of terrible! It's Perl's wonky/shell based way of passing in variables, rather arcane "-e" for file test, use of 1 or 0 for true/false, and doing everything by regex (well that last is not terrible terrible but still) That all reflects Perl's history drawing from shell programming, which I never did much of.

Here is the same logic recreated in PHP

function dateGoneOrEmpty($justwhen){
    $filepath = "entries/$justwhen.txt";
    if(!file_exists($filepath)) return true;
    $buf = file_get_contents($filepath);
    if(str_contains($buf,"MORE")) return true;
    if(ctype_space($buf)) return true;
    return true;
}

(Not optimized at all, just trying to formally recreate the old behaviors)

That's so much cleaner! I also love how PHP splits the difference with globals... you can just write a simple script and everything is a global, but if you reference a global in a function - you can do that, you just have to declare it as "global". That's so much better than javascript's "well we'll just throw it on window." and/or  "just assume there is a global of this name"

(The one thing I loved in Perl I wished showed up elsewhere: use of "eq" and "ne" "gt" and "lt" for string comparisons... I love the mnemonics - it's a string, so the operator is more string-ish)


No comments:

Post a Comment