in reply to Splitting multiple patterns

You could split the line the first time at the space, assigning the name as the first side of the whitespace and put the rest into another variable, then split the $rest variable on the commas:

#!/usr/bin/perl use warnings; use strict; open my $fh, "<", "infos.txt" or die "cannot open infos.txt: $!"; while ( my $line = <$fh> ){ chomp $line; my ( $name, $rest ) = split /\s+/, $line; my ( $age, $gender, $address ) = split /,/, $rest; print "Name: $name\n"; print "Age: $age\n"; print "Gender: $gender\n"; print "Address: $address\n"; print "\n"; }

Output:

Name: Mawts Age: 25 Gender: female Address: melbourne Name: Awts Age: 24 Gender: male Address: sydney

Replies are listed 'Best First'.
Re^2: Splitting multiple patterns
by astronogun (Sexton) on Apr 09, 2012 at 04:35 UTC
    Hi stevieb

    How about if I put the infos.txt file into a array first and then splitting it from there. like first it will open the .txt file then putting it in a array, then split them inside..

    open(INFILE, "<", "infos.txt") or die ("cannot open input: $!"); my @infos = <INFILE>; chomp(@infos);

    How can I split the datas on my @infos? thanks

      It's really not much different. However, slurping in the whole file can run you out of memory if your file is very large.

      #!/usr/bin/perl use warnings; use strict; open my $fh, "<", "infos.txt" or die "cannot open infos.txt: $!"; my @array = <$fh>; close $fh; for my $line ( @array ){ chomp $line; my ( $name, $rest ) = split /\s+/, $line; my ( $age, $gender, $address ) = split /,/, $rest; print "Name: $name\n"; print "Age: $age\n"; print "Gender: $gender\n"; print "Address: $address\n"; print "\n"; }
        Hi stevieb,

        One last question. How about if want to get only the $address? and only print the "Address:"? What I want is to split the Name up to Gender so that it will only read the $address

        Thanks