use warnings; use strict; while () { my ($part1, $part2, $part3, $part4) = $_ =~ /"some text (?:\((.*?)\) )?more text (.*?) and dst text (.*?) -flag (.*?)"/; $part1 ||= ''; print "1: $part1\n2: $part2\n3: $part3\n4: $part4\n"; } __DATA__ "some text (6\'s and 7\'s) more text fred and dst text joe -flag /tmp/filename" "some text more text fred and dst text joe -flag /tmp/filename" #### 1: 6\'s and 7\'s 2: fred 3: joe 4: /tmp/filename 1: 2: fred 3: joe 4: /tmp/filename