Perl:如何引用数组?

时间:2016-03-05 04:29:20

标签: arrays perl

我这里有一个程序,允许用户输入稍后将用作文件名的单词。用户的输入插入到数组中。然后我创建一个简单的菜单,询问用户想要用“文件名”做什么:创建,重命名,复制和删除。使用子程序,我相信我已经成功执行了代码。但是,我在尝试引用数组元素时遇到了麻烦。 简而言之,如何创建,重命名,复制和删除保存在数组中的文件名?我无法解决的问题是带星号的

#!/usr/bin/perl
use strict;
use warnings;
use File::Copy qw/copy/;

my $new;
my $old;
my $file;

print "Enter number of lines\n";
chomp(my $n = <STDIN>);

my @lines;
print "Enter some words!\n";
for (1..$n) {

chomp(my $input = <STDIN>);
#will add the user input at the beginning of the array
push @lines, $input;
}
print "@lines\n";

#create a menu
my $in = '';
print "1. Create\n2. Rename\n3. Copy\n4. Delete\n5. Quit\n";
while ($in ne "quit")
{
  print "\nEnter the your choice:\n";
    chomp($in = <STDIN>);
  print "For which file do you want to $in?\n";
  print "@lines\n";
  **#I need to reference the array here***********************

  if ($in eq "create") {
***How to create the file that the user inputted?*****************
    &createFile;
    print "\nFile has been created\n";
  }
  elsif ($in eq "rename") {
    #print "Enter the old name\n";
     # chomp($old = <STDIN>);
#*********refer to array of FILES*********************
    print "Enter the new name for this file!\n";
      chomp($new = <STDIN>);
    &renameFile;
    print "File has successfully been renamed.";
  }
  elsif ($in eq "copy") {
#********file and array refering***************************
    &copyFile;
    print "Hopefully, the file has beed copied!";
  }
  elsif ($in eq "delete") {
#******refer to file from user*******************
    &deleteFile;
    print "Deleted";
  }
}



#create subroutine
sub createFile {
  open('>' .*****issue here too**) or die "\nCannot create";
}

sub renameFile {
  rename ($old, $new);
}

sub copyFile {
  copy $old, $new;
}

sub deleteFile {
  #unlink *****************************
}

2 个答案:

答案 0 :(得分:0)

第一行是$ line [0],第二行是$ line [1],依此类推......

您可以选择以下用户:

   $line[$in]

答案 1 :(得分:-1)

关于如何引用perl数据结构,请参阅here

$lines[0]; #First line
$lines[1]; #Second line
$array = \@lines; # Get reference to the list of lines
$array->[0]; #First line
$array->[1]; #Second line

创建文件并将数据放入使用中:

open $fh, '>filename';
print $fh @lines;
print $fh @$array; # ... or same for reference

注意$fh

之后没有昏迷