1

I am trying to copy each array elements with slight modification into single string variable in Perl. What I want is to copy each element by adding 0x prefix into string. This is what I have tried so far:

#!usr/bin/perl

  use strict;
  use warnings;

  my @values = (01, 02, 03, 04);
  my $res = "";
  
  foreach my $val (@values) {
    $res = join '', "0x", "$val", ", ";
  }

  print "$res\n";
 
  exit 0;

As a result I got just 0x04,. Wanted result should be like: 0x01, 0x02, 0x03, 0x04

2 Answers 2

3

In your loop you overwrite the string in every iteration. That is why you only get the last value.

You can use join() over the whole array, not just the individual parts of an element. To prefix and zero pad the numbers and get their hexadecimal representation in the array you can use map() and sprintf().

#!/usr/bin/perl

use strict;
use warnings;

my @values = (01, 02, 03, 04);
my $res = '';

$res = join(', ', map({ sprintf('0x%02x', $_) } @values));

print("$res\n");

exit(0);

(Also note, that your shebang was missing the leading forward slash (/). Most likely that's not intentional.)

Sign up to request clarification or add additional context in comments.

3 Comments

I totally understood your code. Just one minor note: Since hex values are not only consisting of numerical values better to use %s instead of %i
The OP probably wants the hex representation of the numbers. For that, use sprintf('0x%02x', $_)
@Emil: If there are numbers in the array and you want the hexadecimal representation of them (which I probably should have guessed by the 0x prefix), you can use x instead of i in sprintf(). I edited the answer.
0

Try in this way:

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

my @values = (01, 02, 03, 04);
my @array;

foreach my $val (@values) {
    push (@array, "0x".$val);
}

print Dumper(\@array);

my $res = join(",", @array);
print $res;

1 Comment

The OP probably wants the hex representation of the numbers. For that, use sprintf('0x%02x', $val)

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.