Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Quick Regex Question

by Anonymous Monk
on Feb 08, 2001 at 00:00 UTC ( [id://57030]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a weird value, say, ^%@|CaD5H . What I need to do is make a file with that name. (The program is generating thousands of files. Filenames are one of the values of the data.) Anyways, the Win32 filesystem doesn't like the | as well as other characters. Is there a quick regex (and its reverse) that will convert non /a-zA-Z0-9_-/ to, say, the hex value? (and back again?)

TIA

Replies are listed 'Best First'.
Re: Quick Regex Question
by Fastolfe (Vicar) on Feb 08, 2001 at 00:09 UTC
    s/([^\w-])/'%'.unpack("H*", $1)/eg; # %5e%25%40%7cCaD5H
    See perlre, pack and unpack. If you need to use another character besides '%', go for it.
      Thanks. I got it working both ways.. works great.
      What does the e do? ( .. ("H*", $1)/eg; )

      I didn't see it in perlre.
      tia

        It turns out that /e is not documented in perlre because /e does not affect the regular expression. Instead, /e is documented in perlop, in the documentation for s/// (near the bottom).
        Odd; I can't find it documented either. Its purpose is to tell Perl to evaluate the right-hand-side of a substitution, instead of just using it as-is. This lets you put code in the right-hand-side of a substitution instead of just text.
Re: Quick Regex Question
by kilinrax (Deacon) on Feb 08, 2001 at 00:11 UTC
    Converting to a hex value is pretty easy:
    perl -e '$_ = q(^%@|CaD5H); s/([^\w-])/sprintf qq(%lx), ord($1)/eg; pr +int'
    Doing the reverse will be a lot more tricky, unless you add a character to the start of each hex replacement to mark it out as such.
      Well if you need to be able to reverse it, why not just convert the whole dang string to hex (like a really conservative version of uuencode), provided the filename won't get too long.

      --
      I'd like to be able to assign to an luser

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://57030]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2024-04-23 12:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found