【问题标题】:Perl: How to reference to an array?Perl:如何引用数组?
【发布时间】:2018-01-07 03:58:06
【问题描述】:

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

#!/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 *****************************
}

【问题讨论】:

    标签: arrays perl


    【解决方案1】:

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

    您可以像这样获得用户选择:

       $line[$in]
    

    【讨论】:

      【解决方案2】:

      关于如何引用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之后没有昏迷

      【讨论】:

        猜你喜欢
        • 2016-02-25
        • 1970-01-01
        • 2021-03-23
        • 1970-01-01
        • 2012-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-29
        相关资源
        最近更新 更多