What's going wrong in your code is that $1 contains the string "0xdf7780", which Perl does not automatically convert to a number. You can use the hex function to convert it to a number first, and then use sprintf to convert the output back to hex:

$line1 =~ /addr:([a-z0-9-]+)\s+/; my $one = $num + hex $1; $one = sprintf "0x%x", $one; $line1 =~ s/addr\:0x.*qospri/addr\:$one qospri/;

However, it's also possible to do it all in one statement, using the special s///e, which runs the replacement part as Perl code and inserts its return value as the replacement, so you can use it to run sprintf directly. I've also used \K and a (?=...) lookahead to exclude those strings from the match, so they're not changed by the replacement.

$line1 =~ s{ addr:0x \K ([0-9a-fA-F]*) (?=\s+qospri) } { sprintf "%x", hex($1)+$num }xe;

By the way, you should always Use strict and warnings, and use proper indentation to make your code easier to read (perltidy can help with that).

Update: I added the /x modifier to the regex to make it easier to read. Also switched from (?=\ qospri) to (?=\s+qospri) to make it equivalent to the original regex.


In reply to Re: Performing addition on hex value extracted from a string by haukex
in thread Performing addition on hex value extracted from a string by syedasadali95

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.