www.webdeveloper.com
Results 1 to 4 of 4

Thread: Syntax explanation

Hybrid View

  1. #1
    Join Date
    Mar 2012
    Posts
    29

    Syntax explanation

    Hi

    I have a rough grasp on OO perl however,
    I would like someone with perl experience to give me an explanation of what the following code is doing?
    I have highlighted in red the lines I would most like explained

    When I run the code the output is c1

    Code:
    package NewObject;
    1;
    sub new{
    my $newobject = {};
    $myobject->{"Apple"} = $_[1];
    $myobject->{"Pear"} = $_[2];
    
    return bless $newobject;
    }
    sub newmethod{
    my $me = shift;
    $me->{"Apple"} = shift;
    $me->{"Pear"} = $_[0];
    }
    
    $my = new NewObject("a1", "b1");
    $my->newmethod("c1", "d1");
    print $my->{"Apple"};
    Regards Maxwell

  2. #2
    Join Date
    Oct 2007
    Location
    Vienna, Austria
    Posts
    393
    Firstly, I believe there's a typo. The two first red lines make little sense with $myobject. I would expect the variable to be $newobject, as declared one line above.

    What the first two red lines do is that they assign to the 'Apple' and 'Pear' keys of the object (which happens to be a hash ref) the parameters to the constructor. So for example if you then call
    Code:
    $obj = NewObject->new('red','green');
    then the following equalities will hold:
    Code:
    $obj->{Apple} eq 'red';
    $obj->{Pear} eq 'green';
    This is because @_ is the array where a subroutine gets its parameters. For more about this, look at perldoc perlsub.

    The second two red lines do the same thing only they use the fact that the shift method returns the first parameter and removes it from the @_ array. Look at perldoc -f shift

  3. #3
    Join Date
    Oct 2007
    Location
    Vienna, Austria
    Posts
    393
    I might add that a method gets the thing that's before the arrow as its first parameter, so when calling
    Code:
    NewObject->new('red','green')
    the "new" method will get "NewObject" as the first parameter ($_[0]) and then 'red' and 'green' as the subsequent parameters ($_[1] and $_[2]). See perldoc perlobj for details.

  4. #4
    Join Date
    Mar 2012
    Posts
    29
    Hi
    Thanks for replying I understand things better now!

    Regards Maxell

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles