Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Append last array element in Perl

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

thanks !

example of what i want :

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

>Solution :

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

use strict;
use warnings;

use Data::Dumper;

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

print Dumper(\@array);

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

print Dumper(\@array);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading