Is there a way for me to get bytes from a file and store it in a Perl array?
有没有办法让我从文件中获取字节并将其存储在Perl数组中?
For example, if my file has 100 bytes, I want to be able to create an array in which each element holds 10 bytes.
例如,如果我的文件有100个字节,我希望能够创建一个数组,其中每个元素包含10个字节。
I know how to create arrays and store lines but I'm not sure on how to get only bytes.
我知道如何创建数组和存储行,但我不知道如何只获取字节。
1 个解决方案
#1
7
The input record separator $/
is normally set to a string (usually newline "\n"
) that indicates the end of each record in the file.
输入记录分隔符$ /通常设置为一个字符串(通常是换行符“\ n”),表示文件中每条记录的结尾。
However, it can also be set (temporarily) to a reference to an integer that specifies the size of fixed-length records.
但是,它也可以(临时)设置为对指定固定长度记录大小的整数的引用。
You are also likely to want to read the file in raw (binary) mode, so your code would look something like this
您也可能希望以原始(二进制)模式读取文件,因此您的代码看起来像这样
use strict;
use warnings;
use autodie;
my @data = do {
open my $fh, '<:raw', 'myfile';
local $/ = \10;
<$fh>;
};
Note that, if it is more convenient, the length can be a string
注意,如果更方便,长度可以是字符串
local $/ = \'10';
or a variable that contains the integer or string
或包含整数或字符串的变量
my $record_size = 10;
local $/ = \$record_size;
#1
7
The input record separator $/
is normally set to a string (usually newline "\n"
) that indicates the end of each record in the file.
输入记录分隔符$ /通常设置为一个字符串(通常是换行符“\ n”),表示文件中每条记录的结尾。
However, it can also be set (temporarily) to a reference to an integer that specifies the size of fixed-length records.
但是,它也可以(临时)设置为对指定固定长度记录大小的整数的引用。
You are also likely to want to read the file in raw (binary) mode, so your code would look something like this
您也可能希望以原始(二进制)模式读取文件,因此您的代码看起来像这样
use strict;
use warnings;
use autodie;
my @data = do {
open my $fh, '<:raw', 'myfile';
local $/ = \10;
<$fh>;
};
Note that, if it is more convenient, the length can be a string
注意,如果更方便,长度可以是字符串
local $/ = \'10';
or a variable that contains the integer or string
或包含整数或字符串的变量
my $record_size = 10;
local $/ = \$record_size;