Search code examples
perlcommand-linestdin

Perl - Command line input and STDIN


I've created this script below for a assignment I have. It asks for a text file, checks the frequency of words, and lists the 10 words that appear the most times. Everything is working fine, but I need this script to be able to start via the command line as well as via the standard input.

So I need to be able to write 'perl wfreq.pl example.txt' and that should start the script and not ask the question for a text file. I'm not sure how to accomplish this really. I think I might need a while loop at the start somewhere that skips the STDIN if you give it the text file on a terminal command line.

How can I do it?

The script

#! /usr/bin/perl

use utf8;
use warnings;

print "Please enter the name of the file: \n" ;
$file = <STDIN>;
chop $file;


open(my $DATA, "<:utf8", $file) or die "Oops!!: $!";
binmode STDOUT, ":utf8";

while(<$DATA>) {
    tr/A-Za-z//cs;
    s/[;:()".,!?]/ /gio;
    foreach $word (split(' ', lc $_)) {
        $freq{$word}++;
    }
}

foreach $word (sort { $freq{$b} <=> $freq{$a} } keys %freq) {
   @fr = (@fr, $freq{$word});
   @ord = (@ord, $word);
}

for ($v =0; $v < 10; $v++) {
    print " $fr[$v] | $ord[$v]\n";
}

Solution

  • You need to do the following:

    my $DATA;
    my $filename = $ARGV[0];
    unless ($filename) {
        print "Enter filename:\n";
        $filename = <STDIN>;
        chomp $filename;
    }
    open($DATA, $filename) or die $!;
    

    Though I have to say, user-prompts are very un-Unix like.