Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Syntax error with loops

by bart (Canon)
on Feb 25, 2004 at 18:32 UTC ( [id://331758]=note: print w/replies, xml ) Need Help??


in reply to Syntax error with loops

Isn't $printnumber the object reference??
Well... your problem seems to be that in Perl, not everything is an object. A number is not an object.

So, you have to use ordinary operators for ordinary variables to make it do what you want. Here that would be something like

$printnumber += 1;
or
$printnumber++;

Just for fun, I'll make $printnumber an object, and have it accept your syntax:

#!/usr/bin/perl -w { package NumberObject; use overload '""' => \&as_string, '0+' => \&as_number, '+' => \&ad +d; sub new { my $class = shift; my $value = shift; bless \$value, $class; } sub as_string { return "" . ${+shift}; } sub as_number { return 0 + ${+shift}; } sub add { my $self = shift; return ref($self)->new($self->as_number + shift); } sub inc { my $self = shift; $$self += shift; } } $\ = "\n"; my $printnumber = new NumberObject(-1); print "initial value:"; print $printnumber; print "looping:"; for (1 .. 10) { inc $printnumber 1; print $printnumber; } print "overload magic (adding 5):"; $printnumber += 5; print $printnumber; print "still an object (adding 2):"; inc $printnumber 2; print $printnumber;
This produces:
initial value:
-1
looping:
0
1
2
3
4
5
6
7
8
9
overload magic (adding 5):
14
still an object (adding 2):
16

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2024-04-24 06:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found