Thomas Bätzler wrote:
> Bob Williams <n...@spam.barrowhillfarm.org.uk> asked:
>> I am trying to split the lines in a file into two halves (at the first
>> space) each half going into an array. The code I have written is below.
> 
>> ---Code---
>> #!/usr/bin/perl
>> use warnings;
>> #use strict;
> 
> use strict; # unless you know what you're doing.
> 
>> #use diagnostics;
>>
>> # perl script to compare two files of md5 checksums
>> #+and extract the lines which differ
>>
>> open (BHF_FILE, "</home/bob/tmp/md5music")
>>      or die "Could not open md5music: $!";
> 
> Better:
> 
> open( my $bfh_file, '<', '/home/bob/tmp/md5music' ) or die ...
> 
>> @bhffile = <BHF_FILE>;
>> close (BHF_FILE);
>>
>> for (my $i = 0; $i <= $#bhffile; $i++){
>>      $bhffile[$i] =~ m/(\s.+) ( .+)/;
>>      push @ukchecksum, $1[$i];
>>      push @uktrackname, $2[$i];
>> }
> 
> If your track names are unique, you're much better off using an associative 
> array ("hash") for your data.
> 
> It also makes comparison with track names and checksums from a second list 
> much easier:
> 
> my %uktrackchecksum;
> 
> while( my $line = <$bhf_file> ){
>   my( $track, $checksum ) = split /\s+/, $line;
>   $uktrackchecksum{ $track } = $checksum;
> }

That split will not do what the OP wants AFAICT. It will take the first
two items that are separated by whitespace, and throw away the rest.

Following the 'do something with one line at a time as opposed to eating
the file all at once' (the regex isn't all that pretty, but its early ;)

...and left in the hash, as I agree that it's more effective, however,
it may be hard to work with later with such random and 'stringy'
information:

#!/usr/bin/perl

use warnings;
use strict;

my %music_store;

while ( my $entry = <DATA> ) {

    $entry =~ m{ (.*?) \s+ (.*) \n }xms;

    my $checksum = $1;
    my $song     = $2;

    # we can work with the data while looping
    # over it

    print "Checksum: $checksum\n";
    print "Rest: $song\n";

    # and stash it away so we can use it later
    # ...each song (key) has a checksum

    $music_store{ $song } = $checksum;

}

# print them out

while ( my ( $song, $checksum ) = each %music_store ) {

    print "$song has checksum: $checksum\n";
}

__DATA__
60196093f7a180d1f2d5fb47ded646be  artists/Abdullah
Ibrahim/Various/abdullah ibrahim - Black Lightning.mp3

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to