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

Hello, I have written a code in Perl. I wanted to know how do I refer to the command line arguments as my input/output files. My code:
#!/usr/intel/bin/perl use warnings; use strict; my $find_flag; #using a flag variable while ( <> ){ if (/^\S/){ #match a line that start wit +h no space if (/^\w+clk\[\d+\]/){ #match requested headline $find_flag = 0; } else{ $find_flag = 1; } } next if $find_flag and /\s+QUALIFIED_CLOCK/; #skips the line req +uested print qq{$_}; #printing ordinary +line }
The command line should be of the form: CODENAME INPUTFILE OUTPUTFILE STRING so my code will edit INPUTFILE, print the result to OUTPUTFILE and replace "QUALIFIED_CLOCK" with STRING. Thanks!

Replies are listed 'Best First'.
Re: Command Line
by toolic (Bishop) on Oct 22, 2008 at 12:39 UTC
    An alternative is to use the core module, Getopt::Long, to handle the processing of command line options. One advantage of named options is that it can be independent of order:
    codename -repl string -in infile -out outfile
Re: Command Line
by holli (Abbot) on Oct 22, 2008 at 12:30 UTC
    #!/usr/intel/bin/perl use warnings; use strict; my $find_flag; #using a flag variable my ($iFile, $oFile, $replacement) = @ARGV; open my $iHandle, '<', $iFile or die $@; open my $oHandle, '>', $oFile or die $@; while ( <$iHandle> ){ if (/^\S/){ #match a line that start wit +h no space if (/^\w+clk\[\d+\]/){ #match requested headline $find_flag = 0; } else{ $find_flag = 1; } } next if $find_flag and s/\s+QUALIFIED_CLOCK/$replacement/; #skip +s the line requested print $oHandle $_; #printing ordinary line }


    holli, /regexed monk/
      Great, thanks! Just one thing - I want the third input - STRING , to be the word that I look for and not replace with. If I don't put anything there I want the code to work as it is, and if I do I need it to look for STRING instead of looking for QUALIFIED_CLOCK...
        I was trying to replace the line mentioned with
        next if ( $find_flag and ( if ($replacement == "") { /\s+QUALIFIED_C +LOCK/ } else { /\s+$replacement/ } ));
        But it writes me "syntax error". I cant understand why... What I'm trying to do is check whether I entered a string and then look for it, and If not, look for QUALIFIED_CLOCK .
Re: Command Line
by gone2015 (Deacon) on Oct 22, 2008 at 12:51 UTC

    OK, you've been shown what to do.

    I was going to suggest that perhaps reading some of the very fine manual would help you... however, when I looked for @ARGV in the online documentation it doesn't exactly leap out at you... but see @ARGV in perlvar. It's an array like any other.

    The <> construct in your fragment is a peice of magic to work through (what remains of) @ARGV treating each item in turn as a file name, opening and reading.