bluedog
bluedog

Reputation: 955

Returning "references" and not values from sub?

I have a sub in perl (generated automatically by SWIG) that I want to return multiple values from. However, I seem to be getting variable meta-data instead of the actual values.

sub getDate {
    my $tm = *libswigperlc::MyClass_getDate;
    ($tm.sec, $tm.min, $tm.hour, $tm.day, $tm.month, $tm.year + 1900);
}

The caller is like this...

my ($sec,$min,$hour,$day,$month,$year) = $s->getDate();
print "$year-$month-$day $hour:$min\n";

The $tm.year + 1900 does return the value as wanted. If I add "+ 1" to the other values, they work as wanted too.

But

print $month;

results in

*libswigperlc::MyClass_getDatemonth

instead of

3

What is the best way to return the values to the caller?

I am a novice perl user - I use C++ normally.

Upvotes: 1

Views: 146

Answers (2)

bluedog
bluedog

Reputation: 955

tchrist - you were right to question the typeglob line. That line was generated by Swig, and I had no understanding of it.

All I had to do was return the typeglob as is...

sub getDate { 
    *libswigperlc::MyClass_getDate2; 
}

Now the caller can access the members like this...

my $tm = myClass->getDate();
print "Year = $tm->{year}";

At least now I understand it just well enough to know to leave it as it is, or to change it to be the way as per the original idea.

Upvotes: 0

Nylon Smile
Nylon Smile

Reputation: 9446

Let's go for a longer answer here:

  1. First of all, are you using strict and warnings pragmas? (use strict; use warnings;) They will save you a lot of time by taking some of your Perl freedom away (To me, without them you're stepping out from freedom into extreme anarchism (: ).

  2. $tm . sec would do this: tries to concatenate $tm with sec. Then what's sec? -If you are using strict pragma, then sec is a sub declared somewhere before the call -If you are not using strict pragma (I guess this is the case) sec is used as a bareword.

  3. What is *libswigperlc::MyClass_getDate? Is it returning an object that's overloading concatenation operator(.) and/or add operator (+) in it? If yes (and specially without strict/warnings pragmas) you may expect any kind of result depending on the definition of the overload functions. Getting a correct result that you are getting by putting + is one of the possibilities.

That's all that comes to my mind, I hope others add their explanations too or correct mine.

Upvotes: 1

Related Questions