in reply to Is there a way to open a memory file with binmode :raw?
G'day stevieb,
I don't have MSWin available, but I can fake it sufficiently for this test with:
use open IO => ':crlf';
Here's four ways to do what you want (plus a fifth just to show what happens when one of those isn't used). There may, of course, be other ways I didn't think of.
#!/usr/bin/env perl -l use strict; use warnings; use autodie; use open IO => ':crlf'; my ($f, $fh); my $mf = \$f; my $test_file = 'pm_1144333_test_file.txt'; open $fh, '>', $mf; print $fh 'hello'; close $fh; print_raw_1('mem: ', $mf); print_raw_2('mem: ', $mf); print_raw_3('mem: ', $mf); print_raw_4('mem: ', $mf); print_raw_5('mem: ', $mf); open $fh, '>', $test_file; print $fh 'hello'; close $fh; print_raw_1('file: ', $test_file); print_raw_2('file: ', $test_file); print_raw_3('file: ', $test_file); print_raw_4('file: ', $test_file); print_raw_5('file: ', $test_file); sub print_raw_1 { my ($prompt, $file) = @_; open my $fh, '<:raw', $file; print '1. ', $prompt, unpack 'H*' while (<$fh>); close $fh; } sub print_raw_2 { my ($prompt, $file) = @_; open my $fh, '<', $file; binmode $fh, ':raw'; print '2. ', $prompt, unpack 'H*' while (<$fh>); close $fh; } sub print_raw_3 { my ($prompt, $file) = @_; use open IN => ':raw'; open my $fh, '<', $file; print '3. ', $prompt, unpack 'H*' while (<$fh>); close $fh; } sub print_raw_4 { my ($prompt, $file) = @_; use open IO => ':raw'; open my $fh, '<', $file; print '4. ', $prompt, unpack 'H*' while (<$fh>); close $fh; } sub print_raw_5 { my ($prompt, $file) = @_; open my $fh, '<', $file; print '5. ', $prompt, unpack 'H*' while (<$fh>); close $fh; }
Here's the output:
1. mem: 68656c6c6f0d0a 2. mem: 68656c6c6f0d0a 3. mem: 68656c6c6f0d0a 4. mem: 68656c6c6f0d0a 5. mem: 68656c6c6f0a 1. file: 68656c6c6f0d0a 2. file: 68656c6c6f0d0a 3. file: 68656c6c6f0d0a 4. file: 68656c6c6f0d0a 5. file: 68656c6c6f0a
And, if I hadn't "faked it", i.e. not including the use open IO => ':crlf'; line, I just get:
1. mem: 68656c6c6f0a 2. mem: 68656c6c6f0a 3. mem: 68656c6c6f0a 4. mem: 68656c6c6f0a 5. mem: 68656c6c6f0a 1. file: 68656c6c6f0a 2. file: 68656c6c6f0a 3. file: 68656c6c6f0a 4. file: 68656c6c6f0a 5. file: 68656c6c6f0a
See also:
and, if you're interested in internals:
— Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Is there a way to open a memory file with binmode :raw?
by stevieb (Canon) on Oct 10, 2015 at 15:40 UTC | |
by tye (Sage) on Oct 10, 2015 at 16:28 UTC | |
by BrowserUk (Patriarch) on Oct 10, 2015 at 18:05 UTC | |
by kcott (Archbishop) on Oct 11, 2015 at 02:21 UTC | |
by tye (Sage) on Oct 11, 2015 at 07:26 UTC | |
by kcott (Archbishop) on Oct 12, 2015 at 03:44 UTC |