Need help translating 2 lines of Perl code to PHP

Discussion in 'Programming' started by Barti1987, Oct 1, 2008.

  1. #1
    It has been a while since I worked with Perl and can't really grasp it. I know how to convert the second line, but I put it there to make it easier to understand.

    
    my @chars = map {chr $_} (0x20 ... 0x7e);
    $text = $chars[int(rand(@chars))];
    $text =~ s/[<>!&]/./g;
    
    PHP:
    Any help or pointers appreciated.

    Thanks,
     
    Barti1987, Oct 1, 2008 IP
  2. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #2
    My Perl is kind of rusty, but that's some of the most convoluted rubbish I've seen for generating one random character between space and null.

    Let's go throught that - the first line creates a map, basically an array of characters running from space (0x20/32 DEC) to ~ (0x7E/126)... the next line chooses ONE random character from that set, converts it to an integer to use it as an index of that original array, returning that character... WTF?

    $text=chr(rand(32,126));

    Should be the equivalent of those first two lines. As perl, it should be:

    $text=chr(rand(32..126));

    I'm not sure why the blue blazes the original code is so convoluted... much less why you'd need so complex a regexp on a single character.
     
    deathshadow, Oct 2, 2008 IP
    Barti1987 likes this.
  3. Barti1987

    Barti1987 Well-Known Member

    Messages:
    2,703
    Likes Received:
    115
    Best Answers:
    0
    Trophy Points:
    185
    #3
    Thank you.

    I tried:

    rand(0x20,0x7e)

    but its giving me numbers. Whats the point of the regular expression if the results are numbers?

    Thanks,
     
    Barti1987, Oct 2, 2008 IP
  4. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #4
    rand will indeed give you numbers, that's why you have to wrap it in chr() to convert those numbers to their ASCII equivalents.

    chr(rand(0x20,0x7e))
     
    deathshadow, Oct 2, 2008 IP