Let's say i have a body of text like this
["What Color",["Red","Blue","Gre开发者_如何学Pythonen","Yellow","Brown","White"]]
What is the regex to match a color
i try this
while ($mystring =~ m,/"(.*?)"/|,|[/"(.*?)"|,|/],g);
print "Your Color is : [$1]\n";
Can someone help me this perl scripts should print
- Your Color is: Red - Your Color is: Blue - Your Color is: Green - Your Color is: Yellow - Your Color is: Brown - Your Color is: White
As this text is a valid json string, you can parse it with JSON:
use JSON;
my $json = '["What Color",["Red","Blue","Green","Yellow","Brown","White"]]';
print "- Your Color is: $_\n" for @{ decode_json($json)->[1] }
Besides being a valid JSON string, it is also a valid perl structure, which can be extracted by evaluating the string. This may not be practical (or safe!) for all the strings out there, but for this particular one, it works:
use strict;
use warnings;
use feature qw(say);
my $h = eval("['What Color',['Red','Blue','Green','Yellow','Brown','White']]");
my $tag = $h->[0];
my @colors = @{$h->[1]};
say "- Your '$tag' is: $_" for (@colors);
Output:
C:\perl>tx.pl
- Your 'What Color' is: Red
- Your 'What Color' is: Blue
- Your 'What Color' is: Green
- Your 'What Color' is: Yellow
- Your 'What Color' is: Brown
- Your 'What Color' is: White
加载中,请稍侯......
精彩评论