Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re^5: RFC: beginner level script improvement (various comments)

by georgecarlin (Acolyte)
on Nov 04, 2013 at 13:25 UTC ( [id://1061124]=note: print w/replies, xml ) Need Help??


in reply to Re^4: RFC: beginner level script improvement (various comments)
in thread RFC: beginner level script improvement

As I said, I'm a self-taught perl user and best considered beginner level =)

I tried explaining my reasoning behind how I accessed the args in subs.
I've been looking into oop because in this script there's a lot of expect usage and I want to create re-uasable and well structured subs. (currently that'snot the case)
Below is a case where I have used shift.

sub set_timeout { my $self = shift; my $to = $self->{timeout}; if (@_){ $self->{timeout} = shift; } return $to; }
In this case shift makes sense imo, although it could have just as well been written like this.
sub set_timeout { my $self = $_[0]; my $to = $self->{timeout}; if ($_[1]){ $self->{timeout} = $_[1]; } return $to; }
The reason I didn't use the index based assignment is that shift feels better here and in the documentation I read about oop they exclusively used shift accessing. However in a different scenario like below I don't think using shift in the if clause makes sense.
sub set_stuff { my $self = shift; if (@_){ $self->{stuff1} = shift; #3 lines for one task $self->{stuff2} = shift; $self->{stuff3} = shift; ($self->{stuff1},$self->{stuff2},$self->{stuff3}) = @_; #1 lin +e, same result regardless of stuff presence } return 1; }
So what I'm saying is I used shift when I felt like it without having a clue whether it's faster or better than index based assignment. =)

Replies are listed 'Best First'.
Re^6: RFC: beginner level script improvement (various comments)
by smls (Friar) on Nov 05, 2013 at 07:32 UTC

    Yes, you should of course use whatever you feel most comfortable with.

    FYI, here are two even shorter ways to write that if clause... ;)

    # using a loop: if (@_) { $self->{$_} = shift for qw(stuff1 stuff2 stuff3); } # using a hash slice (probably the fastest alternative): @$self{qw( stuff1 stuff2 stuff3 )} = @_ if @_;

    (The @ sigil in front of the $self hashref is not a typo - see Slices for more info on that.)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (4)
As of 2024-04-23 23:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found