Specerion has asked for the wisdom of the Perl Monks concerning the following question:

I'm attempting to write a script that would be called as: script.pl file word from a shell. I've seen a lot of examples that show how to do something like this with the file hardcoded, and only a few command line with the 'my' function. I've read the perldoc of 'my' and don't quite understand how to use it.
  • Comment on File and Word as Command Line arguments, Output # of Occurences

Replies are listed 'Best First'.
Re: File and Word as Command Line arguments, Output # of Occurences
by choroba (Cardinal) on Oct 28, 2015 at 00:17 UTC
    If you know how to do it with the file hardcoded, just change that line (probably something like my $file = 'myfile.txt';) to
    my $file = $ARGV[0];

    It's far more common to specify non-file arguments first, i.e. to call the script like

    script.pl word file1 file2...

    with possibly many files listed (cf. grep). Perl makes this approach easy with the diamond operator:

    my $word = shift; while (<>) { # Reads the files line by line, # ... $ARGV contains the filename. }

    You can use eof to reset the count if you want to output the count by file.

    my declares a variable. It's unrelated to the task; it's possible to write the script without using it (which doesn't mean it's a good idea).

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Ahh brilliant, thanks for the tip on the common practice. So if I had a lot of arguments to pass in, shift moves from one to the next every time it is used?
        shift removes the first argument (or array element, if an array was specified) and returns it. The diamond operator iterates over the arguments as specified in I/O Operators.
        لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ