Results 1 to 5 of 5

Thread: Base 64 Encoding in Perl

  1. #1
    Senior Member
    Join Date
    Oct 2003
    Posts
    234

    Base 64 Encoding in Perl

    I want to write a Perl script that encodes a file using Base 64 encoding. The Perl documentation tells you to do this:

    Code:
    use MIME::Base64 qw(encode_base64);
    open(FILE, "/var/log/wtmp") or die "$!";
    while (read(FILE, $buf, 60*57))
    {
          print encode_base64($buf);
    }
    but it only seems to encode the first part of the file and then returns. I was wonderring if anyone else has done something like this before, and if so how you got it to work.

    Thanks in advance!

  2. #2
    Senior Member
    Join Date
    Oct 2001
    Posts
    638
    It's cause you're only reading in the first part of the file. You probably want something more like:

    Code:
    use MIME::Base64 qw(encode_base64);
    open(FILE, "/var/log/wtmp") or die "$!";
    
    while (<FILE>) {
      $buf .= $_;
    }
    
    print encode_base64($buf);
    OpenBSD - The proactively secure operating system.

  3. #3
    Senior Member
    Join Date
    Oct 2003
    Posts
    234
    The Perl docs say to do this:

    If you want to encode a large file, you should encode it in chunks that are a multiple of 57 bytes. This ensures that the base64 lines line up and that you do not end up with padding in the middle. 57 bytes of data fills one complete base64 line (76 == 57*4/3):
    but I tried it anyhow, and it printed out the same value over and over again until it returned. Are you sure that that works?

  4. #4
    Senior Member tampabay420's Avatar
    Join Date
    Aug 2002
    Posts
    953
    if it's a txt File (not sure how encoding line by line will affect binaries) but...

    Code:
    #Include yer lib(s)...
    
    open (FILE, "blah") || die;
    
     @gimmic = <FILE>;
    
    close (FILE);
    
    foreach (@gimmic) { print encode_base64 ($_); }
    yeah, I\'m gonna need that by friday...

  5. #5
    Senior Member
    Join Date
    Oct 2003
    Posts
    234
    I think I know what the probelm is. Of course, I'm on a school computer "Word Processing" , and they don't let you use Perl here, but think this should work:

    Code:
    use MIME::Base64 qw(encode_base64);
    open(FILE, "/var/log/wtmp") or die "$!";
    binmode(FILE);
    
    while (<FILE> ) {
      $buf .= $_;
    }
    
    print encode_base64($buf);
    I think the first didn't work for me because I was reading a binary file. Thanks everyone for the help!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •