Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re^2: 5.40 released

by Anonymous Monk
on Jun 12, 2024 at 19:27 UTC ( [id://11159929]=note: print w/replies, xml ) Need Help??


in reply to Re: 5.40 released
in thread 5.40 released

for(my $i = 0; $i < 10; $i++) { # Note to reader: Yes, could have used a trinary here, but those a +re hard to read # and therefore forbidden in my codebase print "$i is "; if(!iseven($i)) { print "NOT "; } print "even\n"; }

The easiest code to read does not have to be read at all because the comments tell you what's happening. If one must write readable Perl then one should use its features instead writing something that looks like C. This is more perlish and way easier to read:

for (0 .. 9) { print "$_ is "; print "NOT " if not iseven($_); print "even\n"; }

Code should be optimized for efficient execution more than readability. Here Perl does both, since creating blocks is more expensive than postfix logic, especially inside loops. Peace

Replies are listed 'Best First'.
Re^3: 5.40 released
by Danny (Hermit) on Jun 12, 2024 at 21:35 UTC
    He was simply showing some of the features of the 5.40.0 release, not trying to demonstrate some beautiful or optimized code, making such nitpicking seem pretty out of place and off topic.

      I semi-agree with anonymonk here - the Cish cruft got in the way of me seeing the point trying to be made. I saw C code and essentially skipped everything else. I find it really hard to imagine why you would want to write C in Perl as a preferred option. Why not just write C in C?

      However I agree with cavac that the implicit variable should be avoided, but not to the extent of eschewing map and grep etc.

      Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond

        Well, since i needed the iterator VALUE in the code, so for(0..9) was not an option. This is quite often the case in my code. To avoid mixing too many styles of constructs, i limited my coding style to use C-Style.

        Plus, as mentioned, i often port between JavaScript, C/C++ and Perl, as well as doing a lot of Arduino development. For my use cases, for(0..9) is the cruft, proper C-Style loops are the norm ;-)

        But, as i said, that's just the style guide for my own projects.

      I guess you're right about being off topic. Sorry I was just trying to be informative. Was triggered by reading that trinary (sic) is hard to read after seeing a multiple parameter loop in perl that was supposed to be easy to read... 🤷

      $ternary = $can ? be_really_easy : to_read_btw;
        No worries. I'm a big fan of ternary expressions myself. However, I don't get all the hate for for(my $i = 0; $i < 10; $i++). Just because it's not unique to perl doesn't it make it non-perl.
Re^3: 5.40 released
by cavac (Parson) on Jun 13, 2024 at 07:37 UTC

    Implicit variables, e.g. $_, are banned from my project. If you use a variable, you have to name it. This makes it much clearer on first glance on what data you are working. And it makes it much easier to move around.

    I should note that i'm paid to develop commercial software, meaning i always have some junior developers come and go. The goal with my code design is to make it easy to convert them from other languages. And i often have to convert code to (or from) Perl to other languages. "The most perlish way" is nearly always a bad idea, whereas a C-like for loop is available in most languages.

      > Implicit variables, e.g. $_, are banned from my project.

      Does it mean map and grep are banned, too? As is sort?

      map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

        Basic sort is OK. Nearly all complex operations that would map, grep and sort are usually done in the database before Perl even gets its hand on the data.

        Yes, sometimes using implicit variables is, unfortunately, unavoidable because of the way some stuff is designed in Perl. But whereever possible, implicit variables are a no go.

        This is just basically part of the design guidelines i've come up for my projects, just like "always croak never die" and "use English". This may or may not make sense for someone elses projects, and i wouldn't even dare to prescribe my coding style to some random stranger on the internet.

        But for the code i bear responsibility (my own and those of my coworkers that work under me), i decided long ago that, when it comes to design and coding guidelines, i might as well run the whole thing as a dictatorship. A benevolent one, maybe. But as long as its my neck that's on the line, i can at least make sure the gallows are properly engineered to my standards, audited regularly, with the hangmans training up to date...

        Making the code easier to read and understand, even for newbies (and people that are used to other programming languages), certainly helps with making the code more robust and error free. To quote a book i read a few months ago: As a quality-control supervisor for a NASA contractor reminded his workers during the Apollo days, it takes just one “Oh, shit!” to replace a thousand well-done tasks.

      Implicit variables, e.g. $_, are banned from my project. If you use a variable, you have to name it.

      I agree with gramps on this one; implicit variables should be avoided ... but not to the extent of eschewing map, grep, sort etc.

      I should note that i'm paid to develop commercial software, meaning i always have some junior developers come and go

      Senior developers come and go too. What happens today at your company when you are away on leave? What is the company's succession plan if you decide to leave for greener pastures?

      "The most perlish way" is nearly always a bad idea, whereas a C-like for loop is available in most languages.

      It may depend on the company and its size, but I disagree with this general approach. In large companies I've worked for, it was common to have C++ specialists and Perl specialists. I would expect to see Perl code written idiomatically. Ditto for C++. And I would pull a face at code review if I spotted a C-style for loop in Perl code. :-)

      Generally, I'm a fan of chromatic's emphasis on maintainability over "readability", described at Readability vs Maintainability References (update: note the classic "the determined Real Programmer can write FORTRAN programs in any language" and "thankfully there is not so much Fortranish Perl out there" quotes in hippo's reply ;-).

      👁️🍾👍🦟

        In large companies I've worked for

        It's currently just me and two minions. And we have to do Perl, JavaScript, TypeScript, HTML, Template-Toolkit, C/XS (only me), bash scripts and some other stuff. I'm understaffed, overworked and i absolutely love it. We move fast, solve "impossible" problems every week, and the product is becoming sleeker, faster and more capable before our very eyes.

        Tackling a big development project with a tiny team on a tiny budget (and less pay) seems daunting, especially for people from that magic silicon valley place on the other side of the pond. But we have no bureaucracy to speak of, except a coding style guide, a weekly meeting and a simple prioritized todo list. If we need to change something currently in development, we just talk to each other for a couple of minutes and have a working prototype by the end of the week.

        I've worked in big companies before. Yes, you have way more resources at your disposal, you have a bigger team to pull ideas from. But it usually takes ages to get anything decided. And it takes ages to get the request to buy a required hardware approved and even longer for the relevant department to decide on the seller with the best price.

        I like working for small companies a lot more. If we decide to change (=improve) some graphical element over coffee, i can just open Gimp and have the fix ready on our test/demo server in a couple of minutes. If i need another(¹) thermal printer, i can go to the next office, get quick approval from the boss and have our company secretary buy it online with next-business-day delivery.

        What is the company's succession plan if you decide to leave for greener pastures?

        I train my coworkers to the best of my abilities. The code is as maintainable as i'm able to design it. I have strict code guidelines that make it somewhat easy for developers used to other languages to understand my Perl code. Everything i do is maintained in source code repos, including and and all database design changes. There is (basic) documentation. There are at least two people with admin permissions on every of our systems.

        Generally, I'm a fan of chromatic's emphasis on maintainability over "readability"

        Yes. But at least in my personal experience, many people who take over maintenance of software have less experience. In the past, it always helped to keep the language used fairly simple(²). Using an explicit for loop over an array (doing operations step-by-step) is often easier to understand than trying to parse some complex "write-only" map() call. If i have to do something complex and less readable (for example, for performance reasons), i always provide an explanation in the comments, in some cases even accompanied by a commented out step-by-step "easy code" example.


        (¹) I'm the printing specialist, too, writing Perl "drivers" for (mostly) point-of-sales invoice printers. My desk currently sports 3 desktop thermal printers, a bluetooth thermal printer and an A4 laserprinter. Oh, and a point-of-sales terminal with integrated thermal printer. (At home, i also have an old industrial thermo-transfer label printer as well as an USB P-Touch printer i've written code for). So if you ever need something printed, i probably have the required equipment within arms length.

        (²) Think Randall Munroe's "Thing Explainer"

      I use map a fair bit in instances like this:

        $sth_insert->execute ( map { $fields{ $_ } } qw/ITEMNO OPTFIELD AUDTUSER AUDTORG VALUE TYPE LENGTH DECIMALS ALLOWNULL VALIDATE SWSET/ ) or $log->logdie ( "Error with $insert_cmd: " . $sth_insert->errstr );
      In that very limited scope, I feel it's fairly clear what $_ is. Another example:
        my @good = grep { $_->{'result'} != 0 } @list; my @bad = grep { $_->{'result'} == 0 } @list;
      (And I'm sure there's a clever way to do that in one statement, and maybe someone smarter than me will suggest it.) Finally, this is also handy:
        for ( 0..2 ) { defined $item_image_url->[ $_ ] or last; $new_values{ "ITEMIMAGEUR$endings[ $_ ]" } = $item_image_url->[ $_ ] // ''; }
      That's about the largest scope that I use $_ for. After that, I tend to use $k (for key) when I'm iterating over a hash:
        foreach my $k ( keys %DBhandles ) { $DBhandles{ $k }{ sth }->finish; $DBhandles{ $k }{ dbh }->disconnect; }
      I get that having $_ appear in code can be a little odd when the scope is anything larger than Quite Small -- it stops you from grokking the code and makes you go back and figure out what the heck the value is, and where it came from.

      Alex / talexb / Toronto

      Thanks PJ. We owe you so much. Groklaw -- RIP -- 2003 to 2013.

        $sth_insert->execute ( map { $fields{ $_ } } qw/ITEMNO OPTFIELD AUDTUSER AUDTORG VALUE TYPE LENGTH DECIMALS ALLOWNULL VALIDATE SWSET/ )

        This will work but using map just for a hash slice is overkill. You can instead do:

        $sth_insert->execute ( @fields{qw/ITEMNO OPTFIELD AUDTUSER AUDTORG VAL +UE TYPE LENGTH DECIMALS ALLOWNULL VALIDATE SWSET/} )

        🦛

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11159929]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (2)
As of 2024-09-10 01:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.