Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Changing the value of an element of array 3

Status
Not open for further replies.

hello99hello

Programmer
Jul 29, 2004
50
CA
I have this array, and I am trying to change the value of the 4th element. Here is my code:
chomp($array[3]);
if ($array[3] = 'BRO.IN LAW') {
$array[3]= "Brother-in-law";
chomp($array[3]);
print "The new value is $array[3] \n";
}

However, it chages the values to "Brother-in-law" for all the 4th elements of all records in the file.

How can I get it to only change values for the records where the 4th element is 'BRO.IN LAW'.
 
You should be using eq here, not =.

Perl has 2 equality-test operators:
== for numbers (2 ='s)
eq for strings

= is an assignment operator. (1 ='s)

When you say
if ($array[3] = 'BRO.IN LAW')
you are assigning the value 'BRO.IN LAW' to $array[3], then testing whether the assignment worked.
Since it did (why not?), the next statement,
$array[3]= "Brother-in-law";
gets executed.

Why all the chomping? There's no need to chomp $array[3] after you assign to it. The string you're assigning doesn't have a line-terminator on the end.


 
Just a slight nitpick to mikevh's answer. With the assignment, you're not testing whether it worked or not. What is being tested is whether the value of the assignment has a true value.

For example, contrast the results of these examples. In both cases, the assignment is successful but in the first case it has a false value:
Code:
# first example - assigment using false value
print "true\n" if ($val = 0);
print "$val\n";

# second example - using true value
print "true\n" if ($val = 1);
print "$val\n";
 
Thanx guys, I apperaiciate your help.

However, if I want to check the range b/w two vales and return another value. Here is the routine I wrote for this little execise:

chomp($array[3]);
if ($array[3] ==> 4567 and $array[3] <== 4569 {
$array[3]= "FED-CODE2";
chomp($array[3]);
print "The new value is $array[3] \n";
}

Supposing $array[3] is initially 4568, I was expecting it to return FED-CODE2. However, again is chaging it for every element. Please Help.
 

Numbers:
if ( ( $array[3] >= 4567 ) && ( $array[3] <= 4569 ) ) {

String/respectively ASCII-comparison:
if ( ( $array[3] ge 4567 ) && ( $array[3] le 4569 ) )
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top