perl equivalent of python array.array(typecode, ..) -


i trying translate python script perl stuck @ couple of code snipets.

for instance how write following python code in perl? (without using perl array related packages)

# packet here binary string data = array.array( 'h', ( ord( packet[i] ) in range( start, end ) ) ) file.write(data); 

my (failed) attempt:

my @data; foreach $i ( $start .. $end ) {    $data[$i] = ord( substr( $packet, $i, 1) );  # assuming perl's ord = python's ord }  print file @data; 

@ysth, actual input large binary file , in excitment of posting first question here forgot generate sample input , ouput, sorry that. completeness find below sample input , output.

input: ['a', 'b', 'c', 'd'] #think packet contents, start=0, end=4

ouput in python:

> cat py.out | xxd 0000000: 6100 6200 6300 6400                      a.b.c.d. 

output in perl:

> cat pl.out | xxd 0000000: 3937 3938 3939 3130 30                   979899100 

@pedro silva, understand in first line of suggestion replace loop map functionality, effect same. unpack 'w*' returns error w not valid type (perl 5.8.8).

edit

you need clarify you're saying. on python (2.7.2), wrong:

file.write(data) 

because data needs string. think mean instead is:

data.tofile(file) 

anyway, want?

print pack("s*", unpack("c*", "abcd")) # piped through xxd => 0000000: 6100 6200 6300 6400     a.b.c.d. 

have through perldoc -f pack correct template string use. since don't have access w (unsigned wchar), i'm using c (unsigned char). s signed short (corresponding python's h.)

/edit

there no typed arrays in perl. ord returns numeric value of first character of argument.

assuming want, map list resulting splitting $packet on each character @data, transforming each element ord (the argument $_ implicitly given.)

my @data = map { ord } split //, $packet; # or @data = unpack 'w*', $packet;           

optionally, using range different actual lower , upper bounds on $packet:

(split //, $packet)[$start .. $end];    # or  split //, substr $packet, $start, $end # ysth's version 

Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -