首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将perl中的有序数组放回shell中

如何将perl中的有序数组放回shell中
EN

Stack Overflow用户
提问于 2014-10-24 04:40:58
回答 1查看 98关注 0票数 0

我一直在开发一个shell程序,它会询问您想要处理的文件的名称;然后使用perl程序对其中一个选择进行排序。我将文件的shell程序放到perl中,并对文件进行了排序。但是现在我陷入了将文件放回shell并将其保存到新文件中的困境。这是我尝试过的:

Perl:

代码语言:javascript
复制
use strict;
use warnings;

my $filename = $ARGV[0];
open(MYINPUTFILE, $filename); # open for input
my (@lines) = <MYINPUTFILE>; # read file into list
@lines = sort(@lines); # sort the list
my ($line);
foreach $line (@lines) # loop thru list
 {
    print "$line"; # print in sort order
 }
close(MYINPUTFILE);

这将打印排序后的列表。

仅供参考,此代码从shell脚本中获取一个文件并对其进行处理。以下是代码

Shell:

代码语言:javascript
复制
#!/bin/bash
clear
printf "Hello. \nPlease input a filename for a file containing a list of words you would like to use.  Please allow for one word per line.\n -> "
read filename
printf "You have entered the filename: $filename.\n"

if [ -f "$filename" ] #check if the file even exists in the current directory to use
then
    printf "The file $filename exists.  What would you like to do with this file?\n\n"
else
    printf "The file: $filename, does not exist.  Rerun this shell script and please enter a valid file with it's proper file extension.  An example of this would be mywords.txt \n\nNow exiting.\n\n"
    exit
fi

printf "Main Menu\n"
printf "=========\n"
printf "Select 1 to sort file using Shell and output to a new file.\n"
printf "Select 2 to sort file using Perl and output to a new file.\n"
printf "Select 3 to search for a word using Perl.\n"
printf "Select 4 to exit.\n\n"

echo "Please enter your selection below"
read selection
printf "You have selected option $selection.\n"

if [ $selection -eq "1" ]
then
    read -p "What would you like to call the new file? "  newfile   #asks user what they want to call the new file that will have the sorted list outputted to it
    sort $filename > $newfile
    echo "Your file: $newfile, has been created."
fi

if [ $selection -eq "2" ]
then
    read -p "What would you like to call the new file? "  newfile2
    perl sort.pl $filename
    # > $newfile2   #put the sorted list into the new output file that the user specificed with newfile2
fi

if [ $selection -eq "3" ]
then
    perl search.pl $filename
fi

if [ $selection -eq "4" ]
then
    printf "Now exiting.\n\n"
    exit
fi

感谢您的帮助,谢谢!

EN

回答 1

Stack Overflow用户

发布于 2014-10-24 05:38:14

正如评论中提到的(但移至此处以回答表单):

您的Perl脚本在STDOUT上输出结果,这意味着调用的shell脚本可以将其重定向到输出文件。您将使用与您的选项#1类似的内容。

更改:

代码语言:javascript
复制
perl sort.pl $filename

至:

代码语言:javascript
复制
perl sort.pl $filename > $newfile2
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26537053

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档