whatahitson
whatahitson

Reputation: 365

How to refer to perl arguments when looping through them?

Hi I'm trying to use the code written in this answer https://stackoverflow.com/a/1712480/1740992 :

foreach (@ARGV){
   print "file: $_\n";
 # open your file here...
   #..do something
 # close your file
}

I don't know how to refer to the argument. When my scipt was just running on one file I open it by running:

$kml = "adair.kml";
open INPUT, "<$kml";

what do I replace my filename with? I've tried $ARGV[n]

thanks

Upvotes: 0

Views: 713

Answers (3)

dms
dms

Reputation: 817

Your code block:

$kml = "adair.kml";
open INPUT, "<$kml";

should be replaced with:

use strict;
use warnings;

my $kml = $ARGV[0];
open my $input_fh, '<', $kml or die "Couldn't open $kml $!";

if your code is only going to run with one argument.

Upvotes: 0

Sinan &#220;n&#252;r
Sinan &#220;n&#252;r

Reputation: 118118

for my $arg (@ARGV) {
    open my $fh, '<', $arg or die "Cannot open '$arg': $!";
    # ...
    close $fh;
 }

Upvotes: 2

Quentin
Quentin

Reputation: 943207

You're already using it, it is $_.

You can use a named variable instead with:

foreach my $foo (@ARGV){

Upvotes: 4

Related Questions