Truncate an array when you have a ref to it?

A

A. Farber

Hello,

I have an object representing a player:

sub new {
my $package = shift;
my $self = {
.......
CHAT => [[], [], []],
};
bless($self, $package);
}

and its CHAT member holds messages
from 3 other players in an array of 3 arrays.

Then I have a method which sends those
messages over a socket to the player:

$aref = $self->{CHAT}->[0];
push @response, 'chat0=' . join '', @$aref;
$self->{CHAT}->[0] = [];

The last line truncates the sub-array
(after the messages have been sent).

I wonder if I can truncate that array by
using the $aref ? Something like $#xxxx = -1;

Thank you
Alex
 
J

John W. Krahn

A. Farber said:
Hello,

I have an object representing a player:

sub new {
my $package = shift;
my $self = {
......
CHAT => [[], [], []],
};
bless($self, $package);
}

and its CHAT member holds messages
from 3 other players in an array of 3 arrays.

Then I have a method which sends those
messages over a socket to the player:

$aref = $self->{CHAT}->[0];
push @response, 'chat0=' . join '', @$aref;
$self->{CHAT}->[0] = [];

The last line truncates the sub-array
(after the messages have been sent).

I wonder if I can truncate that array by
using the $aref ? Something like $#xxxx = -1;

Yes you could do that:

$#$aref = -1;

Or:

@$aref = ();



John
 
T

Ted Zlatanov

AF> $aref = $self->{CHAT}->[0];
AF> push @response, 'chat0=' . join '', @$aref;
AF> $self->{CHAT}->[0] = [];

AF> The last line truncates the sub-array
AF> (after the messages have been sent).

Actually it assigns a new value to that reference. The old array still
exists with the full contents if you have another reference to it (check
$aref, for instance).

AF> I wonder if I can truncate that array by
AF> using the $aref ? Something like $#xxxx = -1;

Sure:

@$aref = ();

or, equivalently,

@{$self->{CHAT}->[0]} = ();

Ted
 
A

A. Farber

AF>         $aref = $self->{CHAT}->[0];
AF>         push @response, 'chat0=' . join '', @$aref;
AF>         $self->{CHAT}->[0] = [];

Actually it assigns a new value to that reference.  The old array still
exists with the full contents if you have another reference to it (check
$aref, for instance).

AF> I wonder if I can truncate that array by
AF> using the $aref ? Something like $#xxxx = -1;

@$aref = ();

or, equivalently,

@{$self->{CHAT}->[0]} = ();

Oh, you're right. Thank you!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top