user2320229
user2320229

Reputation: 71

How to remove the last character from an array?

Is there a way of removing the very last character from an array?

Just to be clear, I am not asking for every entry in the array to have its last character removed, only the very last entry into the array should have its last character deleted.

I have looked at chop/chomp/push/pop etc but alot is related to removing values from strings.

Upvotes: 1

Views: 6010

Answers (2)

David W.
David W.

Reputation: 107040

The pop and push commands add or remove the entire last entry on arrays. These (and their partners, unshift and shift) don't act on individual characters.

The chomp command only removes \n. It was added in Perl 4.0 to replace the chop command as the standard means of removing the \n characters when you read in a line from a file. This is because chomp doesn't remove any characters if the last character wasn't a \n. This means you can safely chomp a string even if you weren't sure whether or not it had a \n on the end.

The chop command does exactly what you want. It removes the last character no matter what that character is. In earlier versions of Perl, you were suppose to check to see what chop returned to make sure it was a \n character. This is what you want.

The problem you're having is that both chomp and chop will operate not just on scalar context, but also on array and hash contexts too. In hash and array context, they act all all the scalar data (but not the keys in hashes). After all, if I read in an entire file, this is pretty much what I want:

my @file_data = <$file_fh>;  #Reads in the entire file into an array
chomp @file_data;            #Removes all `\n` in one fell swoop

So, when you do:

chop @my_array;

It is doing what Perl thinks you want and not what you actually want -- removing just the last character from the last entry in the array.

What you want to do is specify just the last entry in that array, and just chomp that. There are two ways you can do this:

$my_array[ $#my_array ];
$my_array[ -1 ];

The first uses the fact that $#my_array is equal to the index of the last entry in the array. The second one takes a Perl shortcut where negative entries reflect the end of the array:

$my_array[-1];  #Last entry of the array
$my_array[-2];  #Second to the last entry

You'll see both ways in Perl scripts. Now, you can use chop on just the last entry of your array:

chop $my_array[-1];
chop $my_array[ $#my_array ];

Upvotes: 2

simbabque
simbabque

Reputation: 54323

chop is the right tool, but it takes a list of params. If you pass it an array, all elements will be chopped. Instead, just use the index -1. That always gives you the last element.

my @foo = qw(foo bar baz);
chop $foo[-1];
print Dumper \@foo;

# ['foo', 'bar', 'ba']

From the doc:

If you chop a list, each element is chopped. Only the value of the last chop is returned.

Upvotes: 9

Related Questions