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

I'm trying to finish up an assignment for my advanced perl class using ties. It's a simple program - convert F to C and C to F.

My question is, that I've tied two different variables to two different modules ( please excuse me if my terminology isn't quite right, I'm still learning this bit ). Is it permissible to tie to two different modules?

My problem is arising in that I'm passing a scalar in to the module, in to a referenced scalar, but I can't get it to do anything to the values. My code is:

package Celcius; #use strict; sub TIESCALAR{ my $class=shift; my $data=shift; return bless \$data, $class; } sub STORE{ my $self=shift; my $data=shift; return ($$data*(9/5)+32); } sub FETCH{ my $self=shift; my $data=shift; return $$data; } 1;

Can someone please tell me what I'm missing here? I've looked in a few different perl books, but since there's more than one way to do things, I've gotten a few different examples of code - none of which are the same - and I'm stumped at present.

Thanks!

Replies are listed 'Best First'.
Re: Problems using ties
by RMGir (Prior) on Apr 18, 2002 at 19:26 UTC
    I saw a few problems. Check out perltie for more details as to how this all works.

    The constructor seems fine...

    package Celcius; sub TIESCALAR { my $class=shift; my $data=shift; return bless \$data, $class; }
    Your version of STORE didn't actually STORE the change...
    sub STORE{ my $self=shift; my $data=shift; $$self = ($data*(9/5)+32); }
    And last, FETCH only takes one argument, and it's that one argument you should dereference.
    sub FETCH{ my $self=shift; return $$self; } 1;

    If you're interested, here's the test code I used to try out my version:

    #!/usr/bin/perl -w use strict; use Celcius; my $temp; tie $temp, 'Celcius'; $temp = 0; print "Initial temp is $temp (C)\n"; while(<>) { chomp; $temp = $_; print "Temp is $_ (F) ($temp (C))\n"; }
    As an alternative, you could store the Farenheit temp, and do the conversion in FETCH when you return the value.

    Oh, and I think it's spelled "Celsius", but I'm not sure :)
    --
    Mike

Re: Problems using ties
by Popcorn Dave (Abbot) on Apr 18, 2002 at 23:25 UTC
    Thanks for that! I didn't realize that it made a difference where you did the assignment. I had thought it could go either way.