perl + 如何声明数组 [英] perl + how to declares array
问题描述
以下脚本 (test.pl) 在 myfile.txt 文件的 $first_line[1] 和 $second_line[1] 之间附加 $insert[1] 文本并将输出发送到 output.txt
the following script (test.pl) append $insert[1] text between $first_line[1] and $second_line[1] on myfile.txt file and send output to output.txt
但是如果我将数组声明为
but if I declare the array as
my $first_line[1]=")";
my $second_line[1]="NIC Hr_Nic (";
my $insert[1]="hello world
line 2
line3 "
我明白了
syntax error at ./test.pl line 10, near "$first_line["
syntax error at ./test.pl line 11, near "$second_line["
syntax error at ./test.pl line 12, near "$insert["
Execution of ./test.pl aborted due to compilation errors.
如何声明以下数组?
备注:(没有 my 在数组上,脚本工作正常)
remark: (without the my on the array the script work fine)
莉迪亚
#!/usr/bin/perl
# Slurp file myfile.txt into a single string
open(FILE,"myfile.txt") || die "Can't open file: $!";
undef $/;
my $file = <FILE>;
# Set strings to find and insert
my $count=1;
my $first_line[1]=")";
my $second_line[1]="NIC Hr_Nic (";
my $insert[1]="hello world
line 2
line 3 " ;
推荐答案
你应该使用 my @first_line = ();
来声明一个新的空数组.您不必给出尺寸.
You should use my @first_line = ();
to declare a new empty array. You don't have to give a size.
但是您发布的代码有很多很多问题.例如,如果您只有一个元素,为什么还要使用数组?
But there are many, many things wrong with the code you posted. For instance, if you only ever have one element, why use an array at all?
这篇关于perl + 如何声明数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!