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

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top