Dear Monks,
I came across an unexpected behavior in perl and I would very much like your input on what is happening in my code.
I have an array of which I want to check every element against the keys of a hash containing reference data. Because I want to be able to exclude options (genomes in this example) I want to put a '-' in front of genomes I want to exclude later on. The code below is meant to check if I have provided correct genome names and did not misspell them.
In the first peace of code I am manipulating $_ in a foreach loop. But somehow this ends up manipulating my array @species. The last element which initially contained '-CIOINT' now contains 'CIOINT', the - is removed.
In the code below that I'm doing the same but now I am not manipulating $_. The array is not changed.
I am not working with references so I am very curious as to why the array has changed in the first instance. I'm running perl 5.8.8 on a linux machine. Could someone clarify what happens in the first peace of code? I would be very grateful because it's racking my brain!
John
Below is the isolated code with the faulty and working code in it.
#!/usr/bin/perl use warnings; use strict; my %refspecies = ( HOMSAP => 'Homo sapiens', MUSMUS => 'Mus musculus', CIOINT => 'Ciona intestinalis' ); my @species =('HOMSAP','MUSMUS','-CIOINT'); my @duplicate = @species; # Incorrect working code print "Before processing: @species\n"; foreach (@species) { /^-?(.+)$/; $_ = $1; unless (exists $refspecies{$_}) { # Species not in list die "$_ is not in the species table\n"; } } print "After processing: @species\n"; #Correct working code #Duplicate run with minor code adjustment print "Before processing: @duplicate\n"; foreach (@duplicate) { /^-?(.+)$/; #$_ = $1; Removed this line and changed $_ below in $1. This shoul +dn't matter because I am manipulating $_ in the code above and NOT @s +pecies, but somehow it does! unless (exists $refspecies{$1}) { # Species not in list die "$1 is not in the species table\n"; } } print "After processing: @duplicate\n"; #Output is: #Before processing: HOMSAP MUSMUS -CIOINT #After processing: HOMSAP MUSMUS CIOINT #Before processing: HOMSAP MUSMUS -CIOINT #After processing: HOMSAP MUSMUS -CIOINT # Look at @species element 3. Why is @species changed?
In reply to Changing array by changing $_? by johnvandam
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |