Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

unpack versus split

Status
Not open for further replies.

habicamasuchi

Technical User
May 6, 2005
1
US
I am having trouble using unpack instead of split. I know that unpack is quite a bit faster than split and therefore would rather use unpack. The particulars:

open(FILE,"file") or die "No such file";
open(OUT,">outfile";
while(<FILE>) {
$form = unpack("x145 A1", $_);
next unless ($form eq "O");
$_ = unpack("A1000", $_);
@data = unpack("C*",$_);

The problem is with this last line. I want to split the string (which is 2000 characters long) so that each character will be a element of the array. split(//) works but is really slow. unpack("C*",$_) works but gives me the numerica ASCII values instead of the actual characters. How do I get unpack to split the string into individual characters?
 
Does running map to convert back gain you any speed over the standard split //?
Code:
@data = map chr, unpack('C*', $_);
@data = map pack('C', $_), unpack('C*', $_);

________________________________________
Andrew

I work for a gift card company!
 
Correct me if I'm wrong but you want an array of 1000 elements, each holding a character from the first 1000 characters of a 2000 character string.

If that's the case,
Code:
my $data = unpack("A1" x 1000, $_);

I do question though what on earth you'd need this for.
Also, I'm not sure if the Perl compiler will make the "A1" x 1000 into a constant, so if performance is an issue and you're gonna process lots of records, I suggest you setup a template scalar:

Code:
my $template = "A1" x 1000;
open(FILE,"file") or die "No such file";
open(OUT,">outfile";
while(<FILE>) {
    my $form = unpack("x145 A1", $_);
    next unless ($form eq "O");
    my @data = unpack($template, $_);

Let me know if this works :)

Trojan.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top