in reply to Please fix my writing style

Another perlish solution:

my %teams = do { local $/; <DATA> =~ /^([A-Z\s]+?):\s*(.+)$/mg; };

The do block is most helpful here to override $/ in the block and leave it unchanged elsewhere. local $/; turns on file slurping. A match in list context returns a list of all our submatches in parenthesis, which go to our hash.

Replies are listed 'Best First'.
Re^2: Please fix my writing style
by convenientstore (Pilgrim) on Nov 22, 2008 at 16:43 UTC
    btw, can i do this?
    my %teams = do { local $/; next unless <YB> =~ /^([A-Z\s]+?):\s*(.+)$/ +mg; };
    this code seems to get stuck on lines that doesn't have the format that regex is specifying.. so I wanted to skip them..

      You may want to use dragonchild's solution because it is easier to understand.

      You will need to read up on "do" to understand it better. do is not a loop, using next will only exit the block. Let me try to avoid using do.

      "Slurping" a file means reading all its data into a string. There alot of ways to do that, search for file slurping on Super Search to understand it better.

      Once you have the file data the regexp is easier to understand:

      my $teamdata; for my $line (<DATA>) { $teamdata .= $line; } # If you assign a global match to a list, it stores # everything that matched in parenthesis to that list. # A hash can be created using a list eg: (key, val, key, val) my %teams = $teamdata =~ /^([A-Z ]+): *(.+)$/mg;

      The problem with the code I supplied is \s matches whitespace, including a newline. If you replace \s with just a space character, it will skip the bad lines.

      The important thing to learn is how the global match /<regexp>/g can return a list of results, or the number of matches depending on what you assign it to. See perlretut (ie Extracting matches), perlre, search here, etc.

        i definitely need to read more but your solution works well for me
        thank you
Re^2: Please fix my writing style
by convenientstore (Pilgrim) on Nov 22, 2008 at 16:40 UTC
    thank you guys.. i like both of your sytle.. trying them out now..