Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Only using scalers and references

by stevesnz (Initiate)
on Sep 25, 2008 at 05:20 UTC ( [id://713559]=perlquestion: print w/replies, xml ) Need Help??

stevesnz has asked for the wisdom of the Perl Monks concerning the following question:

Hey I'm about 2 weeks into learning perl. I have several years experience in PHP + javascript + a couple of others.

Coming from other languages, perl is friggin weird. What gets me most is stuff like this:

%hash = ();
$hash{'key'} = 'val';

you initiate the hash with %, and add keys with $, which in my book is wickedly confusing.

now i realise that perl is an old language the evolved from humble beginnings so there's lots of convultion built in, kinda like PHP and its inconsistently named functions. i also realise that perl celetrates the fact that there is more then one way to do stuff. that's cool.

still after banging my head against the wall trying to get my head around most of the 'is it' @ or % or $ or {} or [] or () or \ or whatever issues, it seems to me that BY FAR the most intuitive way to program is to only use scalers and references, i.e.

$str = 'abc';
$hash = {}
$hash->{'key'} = 'val';
$array = [];
push @$array, 'val'; # one of the few times you ever use a @ or a %
print $array->[0];

is it ok to program exclusively like this? everywhere else on this site i see people intialise arrays with @array = ();, so i feel like i'm missing something here?

Replies are listed 'Best First'.
Re: Only using scalers and references
by ikegami (Patriarch) on Sep 25, 2008 at 05:27 UTC

    you initiate the hash with %, and add keys with $, which in my book is wickedly confusing.

    You're thinking of the big picture while you should be looking at the smaller picture. The sigil is not based on the data structure, it's based on the value being being fetch/set. Hash values are scalars, so "$" is used when fetching/setting hash values.

    %hash = ();

    I'm surprised you've ever have to do that. Hashes and arrays start off empty. Do you properly scope your hashes and arrays using my? use strict; will identify your most blatant scoping errors (i.e. where you didn't limit the scope at all).

    is it ok to program exclusively like this?

    Anything abnormal increases the chance of errors and reduces readability.

      >> Hash values are scalars

      yeah, thats what my understanding is and all the more reason to use references exclusively. cos (correct me if i'm wrong) references are the simplest way to get a hash of hashes

      and (again correct me if i'm wrong) you can't pass a hash or array into a sub - it get 'flattened' into a scaler ... though if you pass a reference of a hash in there it survives perfectly intact

      to me it seems like 'original 1987' perl is somewhat hampered and the the reference arrow (->) was created so that perl can do all the stuff that most modern languages do by default

        the reference arrow (->) was created so that perl can do all the stuff that most modern languages do by default

        First, I think the ability to take references and to dereference them has existed for longer than the "reference arrow".

        Second, references have existed in Perl at least since 1994, before Java and JavaScript even existed.

        Finally, you seem to be confusing references (pointers on which arithmetic cannot be performed) and passing by reference (changing a parameter in a function changes it in the caller). Perl always passes by reference.

        that most modern languages do by default

        What "most modern languages" do is a bad thing. It's a compromise to increase program speed. Perl6 has many improvements in that area.


        The rest of this post is a getting off-topic. Just some nits.

        it get 'flattened' into a scaler ...

        No, it gets 'flattened' into a list.   See perlsub for details on what happens with subroutine arguments.

        Exactly. And the french language is hampered as well, with their subject before verb method of specifiying things ;-).

        Seriously, the use of the sigils in perl may be something that is controversial to newcomers (like the spaces-are-syntax feature of python) and there may be reasons that that approach is not the best, but you are looking at it with PHP eyes. And finding fault in places that are just unfamiliar to you

        I get the same feeling when I look at (((((lisp))))) and if I had to program in lisp today, it would probably be a perl program in lisps clothing. And the same phenomenon happens when c or pascal programmers had to adopt c++ years ago and really only programmed c or pascal in the new language.

        Using references exclusively because they are needed for a hash of hashes is like saying "I eat rice exclusively because without it you can't make nigiri sushi". Sounds like flame bait to me. Or do you really use only one data structure for all problems ?

        Naturally 1987 perl was hampered. It was one of the first of the fifth generation languages and had to invent many of the things the newer languages could later do from the start. If it hadn't evolved it would be history by now. For example object oriented features were build in so that perl could do stuff that most oo-languages do by default. The interesting thing is how seamlessly that was achieved in perl without breaking old stuff.

Re: Only using scalers and references
by wfsp (Abbot) on Sep 25, 2008 at 05:58 UTC
    is it ok...?
    Maybe, depends and ymmv. :-)

    I would note though that

    $hash = {};
    is likely to confuse others. At least give it a better name
    $hash_ref = {};
    I also prefer
    push @{$array_ref}, 'val';
    I find it reinforces the idea that an array ref is being dereferenced - but that's just me.

    The often recommended way to pass hashes/arrays to and from subs is as refs. Some would say that if that is the case you may as well start off with refs in the first place. On the other hand, many functions operate on lists and the amount of dereferencing involved could cancel out any benefit.

    It depends.

Re: Only using scalers and references
by Your Mother (Archbishop) on Sep 25, 2008 at 06:14 UTC

    These are just examples but I think it's worth mentioning that these sort of names-

    $str = 'abc'; $hash = {} $hash->{'key'} = 'val'; $array = []; push @$array, 'val'; # one of the few times you ever use a @ or a % print $array->[0];

    -rankle -- me at least -- badly. The idea that a string should be named "string" and hash has to be named "hash," implies that either the variables are undocumented and going to be used in such a large scope that you'd have to go hunting to see where/how they were created or that the coder didn't think much about how the next hacker would read the program on a macro-level.

    Variables are the most basic and easily mastered thing in a language besides math operators. When I inherit code with single letter variable names, or unintelligibly abbreviated ones which save four characters of typing, or those which describe the actual variable instead of its contents and purpose I curse the person who wrote it. Other hackers don't need help differentiating SCALAR from HASH -- at least not after the first few weeks :) -- they need help seeing what the code is supposed to be doing. Choosing good variable and sub names is one of the kindest things you can do for your fellow hackers.

Re: Only using scalars and references
by trwww (Priest) on Sep 25, 2008 at 07:01 UTC

    Coming from other languages, perl is friggin weird. What gets me most is stuff like this:

    %hash = ();
    $hash{'key'} = 'val';

    you initiate the hash with %, and add keys with $, which in my book is wickedly confusing.

    I know you might not believe me now, but it lets you do stuff with simple memory lookups that take lines and lines of procedural code in other languages.

    Is it ok to program exclusively like this?

    As you said, one of perl's mantras is TIMTOWTDI, so my answer to your question is yes.

Re: Only using scalers and references
by Hue-Bond (Priest) on Sep 25, 2008 at 06:26 UTC
    is it ok to program exclusively like this?

    While I'm comfortable using @array and $array[$index], I've also thought about what you say and realized that it seems more homogeneous to me. The only caveats I've found are the functions that work exclusively with arrays or hashes (push, pop, shift, unshift, splice, delete, each, exists, keys, values and maybe some more) and the use of slices, which makes the syntax a bit obscure.

    That aside, I find it very natural to work like that.

    --
    David Serrano

Re: Only using scalers and references
by Lawliet (Curate) on Sep 25, 2008 at 19:46 UTC
    "I have several years experience in PHP"

    I found your problem :P


    I suggest getting used to it. The longer you use Perl the easier it will become.

    Just because you do not understand something does not mean you should find a workaround to avoid learning and comprehending why that something is what it is.</confucius>

    I'm so adjective, I verb nouns!

    chomp; # nom nom nom

Re: Only using scalers and references
by LesleyB (Friar) on Sep 25, 2008 at 08:23 UTC

    Sad to see the modern programming languages haven't taught you how to spell scalar.

Re: Only using scalers and references
by stevesnz (Initiate) on Sep 25, 2008 at 23:09 UTC

    Thanks for all your feedback guys.

    Perl seems like a very powerful language, probably more power then you need for 99% of common business tasks and can make for some unreadable code, but hey it's a hackers language right

    I find myself somewhat attracted to this =)

      Any language can be unreadable.

      Perl's gets a bad rap because it has concepts that don't exist in other languages (like context), and it has a very flexible syntax. If you want to write mud, Perl makes it easy. The good news is that Perl also makes it easy to write clean, maintainable, expressive code.

      To avoid writing hard to read code, hang out here and absorb some coding style tips. Also, read Perl Best Practices--not everything in PBP is gospel, but it has tons of great advice and is well worth the time and price. Super Search for "Perl Best Practices" to find loads of good discussion on the recommendations in the book.

      If you want to write truly scary code, definitely look into Obfuscation. I believe there is an obfu tutorial or two floating around the monastery. Acme::Pony is an inspired effort in this area.


      TGI says moo

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (7)
As of 2024-03-28 10:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found