in reply to Learning classes in Perl

Hi ravi45722

You are a little mixed up; you've copied code snippets meant to illustrate different things and patched them together, but the result doesn't make sense.

Your package will contain the constructor sub new() and your script that uses the package will call new() to create an instance of the object.

Also, even though that tutorial shows package 'File' as an example, it's customary to avoid single-word package names unless they are distinctive; you would be safer with either MyFile or My::File.

Update in response to OP's reply:

Are you sure you're ready to tackle OOP in Perl? Have you already become familiar with packages in general? Here's a simple example of a package in a module and a script that uses it, download it and try it out:

# DayPredict.pm # maps moods to predictions package DayPredict; use strict; use warnings; sub predict { my $mood = shift; if ( $mood eq 'happy' ) { return 'be great'; } elsif ( $mood eq 'sad' ) { return 'get better'; } else { return; # didn't get a mood so return undef } } 1; # module must return a true value
#!/usr/bin/perl # predict_day.pl # Tells what sort of day you will have based on your mood use strict; use warnings; use feature 'say'; use DayPredict; my $mood = $ARGV[0] or die "no mood!"; my $prediction = DayPredict::predict( $mood ); if ( $prediction ) { say 'Your day will ' . $prediction . ', do not worry.'; } else { say 'Cannot read your mood so unable to predict your day.'; } __END__
Usage:
$ perl predict_day.pl happy

Now if you wanted to do the same thing with OOP, making an object for your day, you might do something like this:

# MyDay.pm # Interface to objects representing days package MyDay; use strict; use warnings; sub new { # This is boilerplate code you can copy. # But you'd be better off with a module so you don't have to do it + by hand. # Check out Class::Tiny or Moo my $proto = shift; my $class = ref($proto) || $proto; my $self = {}; bless ($self, $class); return $self; } sub mood { my $self = shift; # If there's an argument provided, set the value, # then in either case, return the current value. if ( @_ ) { $self->{'mood'} = shift; } return $self->{'mood'}; } sub predict { my $self = shift; my $prediction; # Get the mood by calling the mood() method on your object # ... referred to as $self here while you're inside it if ( $self->mood eq 'happy' ) { $prediction = 'be great'; } elsif ( $self->mood eq 'sad' ) { $prediction = 'get better'; } return $prediction; # undef if no mood } 1; # module must return a true value
#!/usr/bin/perl use strict; use warnings; use feature 'say'; # my_day.pl - predicts your day based on your mood use MyDay; my $mood = $ARGV[0] or die "no mood!"; my $day = MyDay->new; # construct a new object $day->mood( $mood ); # set the value of the object attribute # based on this script's argument my $prediction = $day->predict; # call the predict() method on the obj +ect, # which contains your mood stored with +in it. if ( $prediction ) { say 'Your day will ' . $prediction . ', do not worry.'; } else { say 'Cannot read your mood so unable to predict your day.'; } __END__
Usage:
$ perl my_day.pl sad
Hope this is a little clearer now!

Update: Changed 'package must return a true value' to 'module must return a true value', thanks Discipulus.


The way forward always starts with a minimal test.

Replies are listed 'Best First'.
Re^2: Learning classes in Perl
by jdporter (Paladin) on Feb 20, 2016 at 01:48 UTC

    (This is answer is not intended for the OP, as it will no doubt be over his head...)

    To be computer-linguistically pedantic, new is not a constructor, but a factory class method. That is, it's a class method (which in perl means it is invoked with the class name passed as the first argument, rather than an object reference[1]); and it is a factory method, meaning its purpose is to return objects which probably[2] didn't exist prior to the call. POOP does not have constructors. (I can't speak for any other OO frameworks for perl; one or more of them may support something closer to a classical constructor.)

    [1] Of course, there are always exceptions. This is Perl, after all. If the sub is written appropriately, it can be both a class method and an object method. Or both of those *plus* support non-method invocation syntax. CGI commits this bletchery, for example.

    [2] Of course, there are always exceptions. For example, one common pattern is for the factory method of a class to return the same instance always -- the "singleton".

    One consequence of these factoids is that there is nothing inherently special about "new". Using that as the name of the factory method is mere convention. Another consequence is that any method can be a factory method, if it's written to be one. There are no limitations.

    I reckon we are the only monastery ever to have a dungeon stuffed with 16,000 zombies.

      To be computer-linguistically pedantic, new is not a constructor, but a factory class method.

      Meh, if you use it exactly like a constructor, its a constructor I tells ya

        That's fine; you can say the "new" method of the CGI class is a constructor. But (a) you can't necessarily say that the "new" method of the FuQuux class is a constructor, and (b) you can't necessarily say that the "constructor" of the FuQuux class is named "new". Perl does not require either of these to be the case. It remains true that Perl does not have constructors as the term is understood in other OO languages.

        I reckon we are the only monastery ever to have a dungeon stuffed with 16,000 zombies.
Re^2: Learning classes in Perl
by ravi45722 (Pilgrim) on Feb 19, 2016 at 04:18 UTC

    To be frank I don't understand what you said. I am very new to this OOP concept. Please guide to rectify that error. I am taking that example from the  http://perldoc.perl.org/ But still it showing error. I dont understand why?? I am in right side to learn OOP ????

      perlobj should explain this for you.

      #!/usr/bin/perl use strict; use warnings; package MyFile; sub new { my ($class,%args) = @_; my $self = { %args }; bless $self,$class; return $self; } sub print_args { my $self = shift; for (sort keys %$self){ print "$_ = $self->{$_}\n"; } } package main; # create new object my $hostname = MyFile->new( path => '/etc/hostname', content => "foo\n", last_mod_time => 1304974868, ); # call method on object $hostname->print_args();
      poj