CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
help with While statement; and reading with ord

 



odubiel
New User

Mar 25, 2013, 10:41 AM

Post #1 of 3 (393 views)
help with While statement; and reading with ord Can't Post

hello i am needed to figure out how i can write a while statement with that reads reads one character at a time from a input file
A. use ord function to get ASCII code
B. get binary using Sprintf
C. and write 8 bit binary to outfile

i am not sure how to go about this, would i list every character with the ord function to get the ascii code one at a time? im confused and help is a ppreciated. i can post problem if needed.


Laurent_R
Veteran / Moderator

Mar 25, 2013, 11:32 AM

Post #2 of 3 (390 views)
Re: [odubiel] help with While statement; and reading with ord [In reply to] Can't Post

The getc function will read one character at a time from your file, you just need to put it in a while loop.


Code
while (my $c = getc $FILHANDLE) { 
my $ascii_value = ord $c;
# etc. Put there your conversion and
# the writing to the output file
}



(This post was edited by Laurent_R on Mar 25, 2013, 12:57 PM)


Kenosis
User

Mar 25, 2013, 12:39 PM

Post #3 of 3 (386 views)
Re: [odubiel] help with While statement; and reading with ord [In reply to] Can't Post

You can do the following for this:


Code
use strict; 
use warnings;

local $/ = \1;
while (<>) {
print sprintf '%08b', ord;
}


Usage: perl script.pl inFile [>outFile]

The last, optional parameter will direct output to a file.

Example inFile:


Code
ABCD


Results:


Code
01000001010000100100001101000100


Perl takes one byte at a time from the file (implicitly read by <>), since the record separator is set to \1 (see $INPUT_RECORD_SEPARATOR here), and sprintf formats the ordinal value of that byte (implicitly passed to ord in $_) as binary.

Hope this helps!


(This post was edited by Kenosis on Mar 25, 2013, 1:09 PM)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives