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

Regarding style

by footpad (Monsignor)
on Oct 24, 2000 at 22:38 UTC ( #38164=perlmeditation: print w/replies, xml ) Need Help??

Perl contains many shortcuts (or conveniences, if you prefer) designed, in part, to save some typing. For example:

  • Matching regular expressions don't need the leading m--provided forward slash is the delimiter.

  • Subroutines calls don't always need the leading ampersand.

  • The diamond operator (<>) can be used instead of <STDIN>.

Update: Fixed the slash problem (thanks, Fastolfe).

Given some of the recent discussion regarding coding style, is it best to avoid counting on these shortcuts?

My thinking here is based on my experience in other languages. For example, in certain languages, you can occasionally get away with implied typecasting. However, there are times when the results of an implied cast are not what you were after and the novice ends up fruitlessly hunting for a bug in what appears to be perfectly good code.

More practically, I wonder if certain examples (no, I don't have any in mind) reply too heavily on shortcuts.

What do you think? What shortcuts, if any, do you take advantage of and which ones do you specifically ignore (e.g. type the longer form)?

For the record, I try to be as specific as possible, if only to help the hapless novice that has to maintain my code in the future.

Replies are listed 'Best First'.
(Ovid - beware the ampersand) RE: Regarding style
by Ovid (Cardinal) on Oct 24, 2000 at 23:36 UTC
    The ampersand in front of the subroutine name is a very specific feature which can get you in trouble if you're not expecting it. &someSub != someSub();

    If you prefix a subname with an ampersand that sub will be called with the current contents of @_, unless you explicitly state the contents. Consider:

    #!/usr/bin/perl -w use strict; my $test = "Hi, there!"; sub1( $test ); sub sub1 { &sub2 } sub sub2 { print @_ }
    That code happily prints "Hi, there!" (without the quotes), despite an apparent lack of arguments in the sub2 call.


    Join the Perlmonks Setiathome Group or just go the the link and check out our stats.

RE: Regarding style
by Fastolfe (Vicar) on Oct 24, 2000 at 23:17 UTC
    A few points:
    1. It's a "forward slash" or a "slash" (/), not a "backslash" (\).. I don't mean to be anal or nit-picky, but the mis-use of this word causes a lot of headaches.. "aych tee tee pee colon backslash backslash..." -- "no, forward-slash, not back-slash.." -- "the one underneath the vertical bar? ok"
    2. So long as the subroutine is declared before it is used (typically meaning that it has to appear in the source code above the point where it's called), this is true. Mainly it's a style thing.. Use whichever is best for you, but use it consistently.
    3. <> means something different than <STDIN> when @ARGV is non-empty. In this case it iterates through the files and operates on each one independently for data, which is probably not what you always want. It makes it easy to write scripts that operate on files if filenames are given, or STDIN if no filenames are provided.
RE: Regarding style
by footpad (Monsignor) on Oct 25, 2000 at 05:37 UTC

    This is great; I really appreciate the discussion and the links.

    Are there other, similar shortcuts, conveniences, or whatever you wish to call them, that one needs to be aware of or careful in using? (In re-reading the original post, I realize that I wasn't completely clear in the main reason for the message.)

    One reason I am asking is this: a book I am re-reading discussed the diamond as a shortcut (which, thanks to merlyn, I understand that it's not). That didn't sit right. So, I asked.

    Are there other, common misconceptions taught as "the proper way?" (What got me thinking along these lines is an online DBI tutorial from a web development site that a) did not use, b) did not taint, c) did not validate data. After lurking around the last several weeks, I realize how dangerous that is. So, I got to wondering what other "bad habits" I've picked up.)

      Here's one quick way.

      I see a lot of Perl code, and have been around Perl since before the Web, which makes me an old-timer now.

      There's a lot of cargo-cult crap being passed around, and I've seen lots of very scary things, not so much because they are really all that dangerous, but because they keep getting passed around as a bad meme pretending to be a good meme, so scary in the amount of brain cells this mildly bad virus now occupies pushing out actual knowledge or research.

      When I see the same scary thing for the 47th time in my timeline, even if it's just the first time here in the Monestary, I let loose and rail on the poor soul who happens to be the incoming infecting vector, not the source of the plague.

      And then I get downvoted. Down and down and down. How dare I, someone to whom much respect is given, hurt a poor innocent only slightly lost soul?, they scream.

      So, the way to know that something has reached "high cargo cult" status in the real world is to watch what I get downvoted for. It's the things that I'm tired of seeing, and don't care how I try to stop it, because it's reached epidemic proportions in the real world, even if the newbies here don't know that, and therefore don't understand why I'd be so hard on the original poster.

      One clue, from me to you. Hope this helps! Have a nice day!

      -- Randal L. Schwartz, Perl hacker

        How about this, then? Why not add page to your site that explains cargo-cult memes, a correct solution, and why it's correct. As you encounter people who are either victims of bad memes ("This doesn't work, why?"), or people propogating bad memes ("Your problem is this, here's how to fix it."), you can add these to your web page, with well-worded explanations that explain why the meme is bad, what the risks are, and the correct way to do it, and *why*. And perhaps, if you know the original source of the meme, a little history ("The original module required this work around, later version do not, this is not longer required, and in fact, exposes this vulnerability").

        Then, instead of whacking them between the eyes, and leaving many of them stunned, senseless, confused, and annoyed, you can link to your page, and specific article, and re-educate them (and perhaps gain XP, instead of losing it...)

        The reality is this: Just because you say it loudly, or repeat it 4 times, doesn't necessarily mean it's right. If I don't know who merlyn is, you're just another user. And I'm not about to go to research on each and every person who gives me an answer to determine if suddenly they're someone who's opinion I should respect. Lots of people know who you are, but a lot more don't.

        I imagine that the time you would spend writing each rant would be far less than inserting a link to a page that could be re-used each time. Heck, you might could even get your own section in FAQ, or something.


        e-mail jcwren

        fwiw, I take your warnings very seriously. I read them and re-read them until they start to make sense. I am not a groupie, nor a hero-worshipper. I'm just an experienced programmer who recognizes someone with far more experience with a language. You know what you're talking about wrt perl. I don't. Tread into my territory and we can trade roles. Nevertheless, please do not get discouraged because of mindless jerks who'll be the first against the wall when the revolution comes. Take a note from Harlan Ellison, do what you feel is right ahd the rest will follow (as someone just reminded me in CB). Those that matter will recognize the basic integrity and appreciate it.

        ftr, I am, in many ways, a newbie (dare I say, "tyro") in this language. I have been asked by my bosses to produce production ready CGI scripts and it scares me to see just how insecure they are. Not because I'm an idiot, but because I didn't know. Given your earlier warnings, I understand things a little better. But there are many issues that are not completely straight-forward, obvious or clear for the novice. this is a frustratingly subtle language and managers do not appreciate that.

        Please don't stop trying to help.

        -- f

        And if perl had a 'cat' command (or if usenet had XP), you'd probably get downvoted for a UUOC post too :-) Really though, I don't understand people defending bad programming practices, and I'm always open to good advice. I almost always learn something from your posts, and your replies to my posts have almost always fallen into one of three categories:
        • Hey! I wish I thought of that!
        • Hey! I didn't know that!
        • Oops! why did I do that :-)

        So please keep it up, and don't sweat the downvotes; its human nature, which for some reason reminds me of the Simpson's episode where the family is hooked up to electrodes and they repeatedly give each other shocks in a parody(re-enactment?) of that psychology experiment...
        Well, some of us aren't familar with what Cargo-Cult programming is.I did find a YAPC abstract that mentioned it, even though I could not get the entire paper.
RE: Regarding style
by reyjrar (Hermit) on Oct 24, 2000 at 23:31 UTC
    Besides those misunderstandings pointed out by Fastolfe, I'd have to say that the style of the program is pretty much dictated by who, other than you has to maintain it.
    For instance, I just changed jobs, and my old programs were picked up by someone else.. so the code I wrote tended to be much in the "traditional style" of programming, using very little of perl's inherint shortcuts, and I formatted my code to look much like my CS teachers would've wanted. Why? because on the first day, my supervisor (the other perl programmer in the group) took a look at some code I had, and asked "What's this 'use strict' and 'use Socket', do you have to download those from CPAN?
    however, when I do stuff for myself, it tends to be on the light side, utilizing as many shortcuts as I can and trying to be as original as possible while still keeping it simple enough that I don't have to pull out my "Perl In a Nutshell" book everytime I want to know what I was referring to here and there.

    That's just me though, and maybe I'm insane, it a good possibility actually :)

RE: Regarding style
by AgentM (Curate) on Oct 24, 2000 at 23:21 UTC
    Actually, the ampersand is less of a shortcut and more "a feature of perl 4". Its requirement in some situations is easily gotten around by predeclaring your subs. I'm not advocating or attacking its use, just commenting on what eventually became of it (according to the perldocs).

    I don't think anyone uses m// anymore. i imagine that some people don't even know what it is! Languages evolve and perl is a language. Since m// is arguably the most used regex function, I don't disagree that it's use is optional.

    The "diamond operator" is used to save five keystrokes. Whether this is good or evil is irrelevant. use whichever is more obvious in context to you. A well-weathered JAPH will link them in his head instantaneously. No problem.

    I think there are many more such "shortcuts", such as cutting down on parentheses in functions. Also, I jokingly consider all of the awk-inherited variables to be very nice shortcuts that I enjoy alot. Thanx awk!

    Also, another great shortcut can be found under this link.

    AgentM Systems nor Nasca Enterprises nor Bone::Easy nor Macperl is responsible for the comments made by AgentM. Remember, you can build any logical system with NOR.
      I have to disagree on a couple of those.

      First of all the diamond operator does not just save 5 keystrokes. Instead it allows you to build filter programs that have a standard (and well-defined) behaviour without your having to build logic to open, test the open, read, close, test the close, get the next filename, etc. When you need it, it is very nice to have. Of course people who use it to avoid writing STDIN are being silly.

      But I use the diamond, and not for obfuscation.

      As for m operator, I use it as well. Why? Well if I want to match a pattern with forward slashes in it, it is often very nice to use m and a different delimiter. So I don't use it often, but unless I am nobody...

        Continuing on the diamond theme, I usually flag "dangerous" anything during code reviews that look like:
        print "Some prompt? "; $input = <>;
        Why? Because that program works fine when you run it without command-line arguments. But what happens when some other part of the program needs a command arg for a toggle or something? Oops!

        And saying "well, sometimes I want to get stuff from files instead of STDIN" doesn't fly, because then you get the extra prompts!

        For me, the only proper combination is:

        • print "..."; $input = <STDIN>;, or
        • $input = <>;

        In other words, if you're interacting, use the explicit filehandle. Otherwise, suck from diamond.

        -- Randal L. Schwartz, Perl hacker

        Don't consider what i say a personal attack- in the end it is a stylistic matter. If you ant to build a filter system using the diamond operator, go right ahead- but again, it's simply a matter of taste, not code quality or obfuscation. Honestly, the only reason I mentioned m is because I haven't seen it in code for quite a while and you will never encounter a situation where it is required.
        AgentM Systems nor Nasca Enterprises nor Bone::Easy nor Macperl is responsible for the comments made by AgentM. Remember, you can build any logical system with NOR.
      I don't think anyone uses m// anymore. i imagine that some people don't even know what it is! Languages evolve and perl is a language. Since m// is arguably the most used regex function, I don't disagree that it's use is optional.

      Let me ask you this...would you downvote code if it used an m instead of leaving it out?

RE: Regarding style
by myocom (Deacon) on Oct 25, 2000 at 05:00 UTC

    The topic of when to use & and when to skip it was discussed here a couple of months ago, and has some good reading in it.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlmeditation [id://38164]
Approved by root
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (6)
As of 2017-02-19 21:22 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (293 votes). Check out past polls.