In a message dated Mon, 24 Sep 2001 10:07:45 AM Eastern Daylight Time, "Pete Sergeant" 
<[EMAIL PROTECTED]> writes:

> How do I insert $scalar into position $x of @array, where $x is smaller than
> $#array?

What about...

#!/perl
# Script:   insert
# Author:   Nelson Fleet
# Date:     09/26/2001
# Purpose:  Insert scalar into an array

print "Enter strings on separate lines to populate array with scalars\n";
print "CTRL-Z on new line to signal EOF\n";

chomp(@old_array = <STDIN>);
print "\n"; # Workaround for ActivePerl bug

print "\nYour array: \n";
foreach $element (@old_array) {
  print $element . "\n";
}
print "\n";

print "Enter a string to insert into array: ";
chomp($insert_str = <STDIN>);
print "Enter position of insert: ";
chomp($insert_pos = <STDIN>);

$old_pos = 1;
$new_pos = 1;

while ($old_pos <= @old_array) {
  if ($old_pos < $insert_pos) {
    @new_array[$new_pos - 1] = @old_array[$old_pos - 1];
    $new_pos = $new_pos + 1;
  } else {
    @new_array[$new_pos - 1] = $insert_str;
    $new_pos = $new_pos + 1;
    @new_array[$new_pos - 1] = @old_array[$old_pos - 1];
    $new_pos = $new_pos + 1;
  }

  $old_pos = $old_pos + 1;
}

print "\nYour array with inserted element: \n";
foreach $element (@new_array) {
  print $element . "\n";
}



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to