Hello everyone. I'm writing a perl script to implement some active content on my website. Does anyone know if there is a source code library to convert an integer variable to an equivalent character string? I've managed to do the reverse, i.e.

sub char_2_int{
for ($c = 0; $c < 4; $c++)
{
$d = 3 - $c;
$e = 10**$d;
if ($data[$c] == 0) {}
elsif ($data[$c] == 1) {$hit_count = $hit_count + (1 * $e)}
elsif ($data[$c] == 2) {$hit_count = $hit_count + (2 * $e)}
elsif ($data[$c] == 3) {$hit_count = $hit_count + (3 * $e)}
elsif ($data[$c] == 4) {$hit_count = $hit_count + (4 * $e)}
elsif ($data[$c] == 5) {$hit_count = $hit_count + (5 * $e)}
elsif ($data[$c] == 6) {$hit_count = $hit_count + (6 * $e)}
elsif ($data[$c] == 7) {$hit_count = $hit_count + (7 * $e)}
elsif ($data[$c] == 8) {$hit_count = $hit_count + (8 * $e)}
elsif ($data[$c] == 9) {$hit_count = $hit_count + (9 * $e)}
}
}

where $data and $hit_count are the character and integer variables respectively. The int_2_char job is proving a bit harder. Any help would be appriciated. Thanks.

Steven.

I don't understand what that sub routine does or what you are asking. Please explain your question some more.

Hello Kevin. What I mean is, is there a library function that you can pass:

$variable_1 = 1234 (type: integer)

and it will return:

$variable_2 = "1234" (type: character)

Steven.

After doing some reading I've found the answer:

$variable_2 = sprintf("%u", $variable_1);

Where $variable_2 and $variable_1 are of type character and integer, respectively.

One of the beautiful things AND at the same time, one of the ugly things about perl is that it does conversions on the fly - by YOUR usage.

here's a snip of calendar code that converts an integer to a character with leading zero:

 foreach $day (@mymonth) {
   my $LinkDay=$mymonth[$counter];
    if ($LinkDay < 10) {
      $LinkDay = "0$LinkDay";
    }

to get chars to ints... i've just used them as such.

g'luck!

perl will drop leading zeros in numbers, but you can stringify numbers to retain the leading zeros or use sprintf() or printf() to pad numbers with leading zeros.

perl will almost always know when to treat digitis as numbers or strings.

my $var = '01';
my $var2 = '03';
print $var + $var2;

prints: 4

my $var = '01';
my $var2 = '03';
print $var . $var2;

prints: 0103

Thanks for the advice. I guess this means I wasted my effort with that little subroutine. However, at least you know for sure whats going to happen when you implement the conversion yourself.

Steven.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.