Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Is it ok to assign a popped value to a variable as shown.

by perl514 (Pilgrim)
on Dec 05, 2011 at 13:29 UTC ( [id://941841]=perlquestion: print w/replies, xml ) Need Help??

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

Hi, I am trying to understand how the push and pop functions work in Perl. Here is the script I have written:
#!/usr/bin/perl use warnings; use strict; my @array = qw(Book Novel Magazine Guide); print "\@array has @array so total:",scalar @array,"\n"; push @array,"LFY"; print "Now we have @array\n"; shift @array; print "Now we have @array\n"; my $saved = pop @array; print "Now we have @array and I have saved $saved\n"; unshift @array, "LFY"; print "Now we have @array\n";
And here is the output:
C:\perl>perl practice.pl @array has Book Novel Magazine Guide so total:4 Now we have Book Novel Magazine Guide LFY Now we have Novel Magazine Guide LFY Now we have Novel Magazine Guide and I have saved LFY Now we have LFY Novel Magazine Guide
Its working like expected, but just wanted to know if its a good practice to do my $saved = pop @array or is there a better way to do it? Are there any other suggestions you would have? I know this is a very simple script, no rocket science but just wanting to ensure that I pick up the correct habits early.

Replies are listed 'Best First'.
Re: Is it ok to assign a popped value to a variable as shown.
by jmcnamara (Monsignor) on Dec 05, 2011 at 13:41 UTC

    That is perfectly acceptable syntax. There are (as usual) other ways to do it but this is the intended function of pop() so use it with confidence.

    --
    John.

Re: Is it ok to assign a popped value to a variable as shown.
by hardburn (Abbot) on Dec 05, 2011 at 13:38 UTC

    Nothing wrong with it. In practice, you'll probably do this in some kind of loop, but this script is fine for showing the idea.


    "There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.

Re: Is it ok to assign a popped value to a variable as shown.
by johngg (Canon) on Dec 05, 2011 at 15:28 UTC

    As others have mentioned, handling arrays like this in some sort of loop is a common idiom. Something that can trip you up is the distinction between "true" and "defined" which can terminate your loop early if you don't take care. Consider the two following snippets:-

    knoppix@Microknoppix:~$ perl -Mstrict -wE ' > my @arr = ( 7, 28, -8, 0, 12, 67 ); > while ( my $val = shift @arr ) > { > say $val; > }' 7 28 -8 knoppix@Microknoppix:~$
    knoppix@Microknoppix:~$ perl -Mstrict -wE ' > my @arr = ( 7, 28, -8, 0, 12, 67 ); > while ( defined( my $val = shift @arr ) ) > { > say $val; > }' 7 28 -8 0 12 67 knoppix@Microknoppix:~$

    Note that in the first example, the loop terminates when accessing the fourth element. This is because the value of that element is zero which means the expression my $val = shift @arr tests as "false" so the while loop finishes earlier than you might expect. Adding a test for defined overcomes this problem in the second snippet.

    I hope this is helpful.

    Cheers,

    JohnGG

Re: Is it ok to assign a popped value to a variable as shown.
by TJPride (Pilgrim) on Dec 05, 2011 at 13:57 UTC
    This is really more a question of aesthetics and coding practice than whether it works or not. Should "my" just be thrown into the middle of the code, where it's nearest to where the variable is needed, or stated at the top, where it's easier to see all your variables and where the "my" doesn't cause things to potentially not line up? For instance, if you were doing something like this:

    my $saved = pop @array; print "Now we have @array and I have saved $saved\n"; $saved = pop @array; print "Now we have @array and I have saved $saved\n";

    Personally, I like declaring at the top, especially if a variable is used several times, but others prefer declaring at the point at which the variable is first used. I still haven't figured out which method is really superior.

    Here's a few more samples of interesting things you can do with arrays:

    Using the standard output variable instead of declaring a new one:

    $_ = pop @arr; print "Value popped is $_\n";

    Cycling through the array, method 1 (each value is put in standard output variable in turn):
    print "Value is $_\n" for @arr;

    Cycling through the array, method 2 ($# represents the subscript of the last item in the array):
    print "Value is $arr[$_]\n" for 0..$#arr;

      Should "my" just be thrown into the middle of the code, where it's nearest to where the variable is needed

      Absolutely yes! Always declare variables in the smallest possible scope. It makes the life time of the variable clearer and makes it easier to see initialisation. Both are very important for making the intent of code easer to understand.

      "Prettiness" of the code is great for Poetry, but is generally not a large factor in understanding the code and at the end of the day that is what determines how easy it is to write the code correctly and debug it if there are errors.

      On a related note, it is always worth spending the time to find a variable name that is "just right" because the time is really spent thinking about what the variable is for and how it fits the code. For trivial code the time spent is likely to be trivial, and for complicated code the extra time spent finding the right name is well justified. Later the time spent up front is likely to recouped many fold by saving time trying to figure out what the code is doing while validating the code or debugging it.

      True laziness is hard work
Re: Is it ok to assign a popped value to a variable as shown.
by educated_foo (Vicar) on Dec 05, 2011 at 14:08 UTC
    Don't worry so much about "correct habits" and "good practices" -- doing so usually just leads to paralysis over meaningless questions like "what should I name this variable?" or "should I put a space here?". Remember that you're writing code to solve a problem, not to win a fashion contest, and you'll do fine.
Re: Is it ok to assign a popped value to a variable as shown.
by perl514 (Pilgrim) on Dec 05, 2011 at 14:56 UTC
    Hi Everyone, Thank you very much for taking time to reply. I am liking this place and Perl :). And yeah, the replies came blazing fast. TJPride, thanks for that snippet. I didn't know that was possible. educated_foo, I just recently started learning Perl and one thing I keep hearing that a script can be written in many different ways. Was just trying to find out a standard agreed upon practice and not trying to muck up stuff. Thanks for your reply.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (2)
As of 2024-04-24 14:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found