t-rex has asked for the wisdom of the Perl Monks concerning the following question:

hello monks,

I have an array where I need to convert every even index element to hex , I have written a code but the output is not what i expected

my @a = "1 10 5 345 2 12"; my $indx=1; foreach my $ind (@a) { print "IND = $ind and index = $indx\n"; if ($ind%2==0) { $ind = sprintf("0x%x",$ind); } $indx++; } print "final conversion input array = @a\n";

actual output : 1 0xa 5 345 0x2 0xc

expected output : 1 0xa 5 159 2 0xc

please let me know where I am going wrong ?

edit : i got my error , just because of same names i made a silly mistake and couldn't see , sorry for the trouble guys

Replies are listed 'Best First'.
Re: decimal to hex in an array
by choroba (Cardinal) on Feb 21, 2017 at 10:55 UTC
    Don't use similar names for different things. You can confuse them, as you did. The condition should have been
    if ($indx % 2 == 0) # ^

    Also, the initialization of the array is wrong, it creates just one element. Change it to

    my @a = qw(1 10 5 345 2 12);

    or

    my @a = (1, 10, 5, 345, 2, 12);

    or

    my @a = split ' ', '1 10 5 345 2 12';
    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

      hey, i got my error, it was a silly mistake as u pointed out, the array doesn't come in this form i just tried to simplify things hence I wrote it like this, thanks.

Re: decimal to hex in an array
by Eily (Monsignor) on Feb 21, 2017 at 10:38 UTC

    Well, you only convert even elements to hexadecimal, 345 is not even so it does not get converted to 159 (or actually 0x159).

    I don't understand how you expect 2 to not be converted to 0x2 though.

Re: Solved : decimal to hex in an array
by BillKSmith (Monsignor) on Feb 21, 2017 at 14:06 UTC
    Your code is correct except for mistakes already corrected. It is still very confusing. Your $indx is one off from the array index therefore odd and even are the opposite of what a Perl programmer expects. Your $ind is an alias for an array element. This is what you intend, but readers can easily overlook that point. (You may be that confused reader in a few weeks.) A clearer style loops on the index and makes the indexing explicit.
    use strict; use warnings; my @a = ( 1, 10, 5, 345, 2, 12 ); foreach my $indx (0..$#a) { next if !($indx % 2); $a[$indx] = sprintf '0x%x', $a[$indx]; } print "final conversion input array = @a\n";
    OUTPUT: final conversion input array = 1 0xa 5 0x159 2 0xc
    Bill