On 3/27/2004 9:15 PM, R. Joseph Newton wrote:

Cool.  Somehow, though It seems {6 * 1 == 12 / 2}-ish.  By the time the variable
is effectively accessed, the text is there.

I never said that it was usefull ;-)


Greetings! E:\d_drive\perlStuff>perl
open IN, 'some_nonexistent_filename' or print $!;
^Z
No such file or directory

What is intriguing to me in this is that an overloaded operator wouuld be
attched to a variable.  this sounds like it gets into prtions of Perl that I've
never really delved into.  Is $! actually sored as a number?

As John pointed out, it is stored as both a number and a string. Here is a small example of how you can do something similar in your own code. See 'perldoc overload' for more info.


#!/usr/bin/perl

package NumStr;

use strict;
use warnings;

use overload
  '""' => \&stringify,
  '0+' => \&numify,
  fallback => 1;

sub new {
  my ($class, $num, $str) = @_;
  return bless {
    num => $num || 0,
    str => $str || '',
  }, $class
}

sub numify {
  my $self = shift;
  return $self->{num};
}

sub stringify {
  my $self = shift;
  return $self->{str};
}

package main;

use strict;
use warnings;

my $ns = NumStr->new(42, 'The Answer to Life, the Universe, and Everything');
printf("as number = '%d', as string = '%s'\n", $ns, $ns);


__END__

You can simulate more closely with XS:

#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"

int
_get(pTHX_ SV *sv, MAGIC *mg)
{
/*
    IF this is a std error lookup
      get errno and store in NV slot,
      then call strerror and store in PV slot.
    ELSE
      a custom error has been stored; do nothing
    END
*/
    return 1;
}

int
_set(pTHX_ SV *sv, MAGIC *mg)
{
/*
    store custom errno in NV slot
    set global flag so _get() knows this is not a std error lookup
*/
    return 1;
}

MODULE = StrError PACKAGE = StrError

void
create(num, str)
        SV *num;
        SV *str;
    PREINIT:
        SV    *sv;
        MAGIC *mg;
    CODE:
        sv = get_sv("StrError", TRUE); /* creates $main::StrError */

sv_magic(sv, 0, '\0', "StrError", 8);

        mg = mg_find(sv, '\0');
        if (mg != NULL) {
            mg->mg_virtual->svt_get = &_get;
            mg->mg_virtual->svt_set = &_set;
        }

        sv_setnv(sv, SvNV(num));
        sv_setpv(sv, SvPV_nolen(str));
        SvNOK_on(sv);



--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>




Reply via email to