Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2024-04-18 07:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found