Home > Blockchain >  Append last array element in Perl
Append last array element in Perl

Time:12-03

i want to add a newline to the lastest element of an array i have tried this :

$array[-1] .= "\n";

but it doesn't work and i get the following error message :

Modification of non-creatable array value attempted, subscript -1

i have tried a few other methods as well (without .=), without success. should i try splice ?

thanks !

example of what i want :

@array = (
  "one",
  "two",
  "n",
  "last\n",  # i want the newline to be added here
);

CodePudding user response:

You can use $array[-1] .= "\n"; to change last entry but make sure you are checking if array is not empty.

Error message Modification of non-creatable array value attempted, subscript -1 has a pretty good explanation here:

You tried to make an array value spring into existence, and the subscript was probably negative, even counting from end of the array backwards.

use strict;
use warnings;

use Data::Dumper;

my @array = (
  "one",
  "two",
  "n",
  "last",
);

print Dumper(\@array);

if ($#array != -1) {
    $array[-1] .= "\n";
}

print Dumper(\@array);

EDIT: As it was correctly mentioned in comments, the problem was not necessarily using -1 instead of $#array as both of those will access last value, but missing if statement checking if array is empty, answer was adjusted to remove unnecessary comment that might be misleading so it is more focused on the actual reason for error.

CodePudding user response:

$array[-1] is the last element of the array.

But what's the last element of an empty array? This unclear message is the result of trying to modify the last element of an empty array.

$ perl -e'my @a = qw( a b c ); $a[-1] .= "\n";'

$ perl -e'my @a;               $a[-1] .= "\n";'
Modification of non-creatable array value attempted, subscript -1 at -e line 1.

You can check if the an array is nonempty using if ( @array ).

  • Related