Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I resolve the warning "Use of assignment to $[ is deprecated"?

Tags:

perl

I have a program that I downloaded from an older computer to a newer one. It has the following snippet of code:

#!/bin/perl -w

use strict;

$[ = 1;    # set array base to 1
$, = ' ';    # set output field separator
$\ = "\n";    # set output record separator

However, when I try to run the script I get the following error message:

Use of assignment to $[ is deprecated at ./test.pl line 5.

Any idea on how to resolve this?

I am using the following version of perl:

This is perl 5, version 16, subversion 3 (v5.16.3) built for x86_64-linux-thread-multi
like image 944
jms1980 Avatar asked Dec 20 '16 00:12

jms1980


2 Answers

The use of $[ has been discouraged, deprecated, and all but disallowed. See it in perlvar (it is in Deprecated and Removed Variables section) and see the core arybase where it's been moved.

Still, if you must, you can disable this particular warning category   (Update: only in pre-v5.30)

use strict;
use warnings;

# Restrict the scope as much as possible
{ 
    no warnings 'deprecated';
    $[ = 1;                               # NOT possible in v5.30+
    
    # ...
}

Now it will not print that warning, and it will work since it is still legal. (Not in v5.30+)

Note that this also changes other offsets, for strings for example, but not yet some others. It is a very, very old "feature," please read the documentation.

I'd strongly recommend rewriting the script, if at all possible.


  Still the same status in v5.30   ... but:   "Assigning non-zero to $[ is no longer possible".

Thus you cannot anymore assign, regardless of warnings or errors (those can be suppressed or handled). Then either rewrite the script or use Array::Base if you must work with that offset, as in mob's answer

like image 62
zdim Avatar answered Oct 15 '22 16:10

zdim


The module Array::Base implements the array index offset feature in modern versions of perl. For a self-constrained script, beginning the script with

use Array::Base (1);

should behave pretty similarly to an older script that says

$[ = 1;

at the top, but see the docs for some potentially important disclaimers.

like image 20
mob Avatar answered Oct 15 '22 16:10

mob