0

I am trying to loop through two equally sized arrays, and replace a string with the elements found at each index.

The loop is only doing the first element.

#!/usr/bin/perl
use strict;
use warnings;

# SQL statement for string replace
my $insert = "INSERT INTO table ( JOB, URI ) VALUES ( 'JOB', 'URL' );";
#array of jobs
my @jobs = ("job1", "job2");
#array of url's
my @urls = ("http://www.yahoo.com", "http://www.google.com");

# for each job replace the "URL" with a url from 
# the url array, then print the new sql insert statement
for( my $i = 0; $i <= $#jobs; $i++ ){
    $insert =~ s/URL/$urls[$i]/g;
    print $insert."\n";
}

EDIT- Using $i<=$#urls now has the correct loop size, but the call to $urls[$i] never gets a different element in that array. Its always the same element

I think this is an issue with the string replace I am doing, the loop will print out the elements as expected, but not when I use the counter in the string replace.

4 Answers 4

3

After the first iteration, $insert doesn't content anymore URI

change your loop as:

for( my $i = 0; $i <= $#jobs; $i++ ){
    my $temp = $insert;
    $temp =~ s/URL/$urls[$i]/g;
    print $temp,"\n";
}
Sign up to request clarification or add additional context in comments.

Comments

1

To answer the issue with the string replace on the insert statement I had, I was trying to change the text in that string, and next loop doing the same search and replace, but there was no longer URL in the string to match on, I should have move that variable to inside the loop.

#!/usr/bin/perl
use strict;
use warnings;

#array of jobs
my @jobs = ("job1", "job2");
#array of url's
my @urls = ("http://www.yahoo.com", "http://www.google.com");

# for each job replace the "URL" with a url from 
# the url array, then print the new sql insert statement
for( my $i = 0; $i <= $#jobs; $i++ ){
    # SQL statement for string replace
    my $insert = "INSERT INTO table ( JOB, URI ) VALUES ( 'JOB', 'URL' );";
    $insert =~ s/URL/$urls[$i]/g;
    print $insert."\n";
}

Thanks to all who helped.

Comments

0

$#jobs get the last index position of last element, 1 in your case. The loop then is from 0 to 0. Use @jobs instead, that get the total number of elements, and would do a loop between 0 and 1.

Comments

0

Try doing this :

foreach my $i (0 .. $#jobs) { print "$i\n"; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.