« MechanicalTurk/Command/SetQuestionPostValidationOnError.pm
↑ Summary
MechanicalTurk/Command/ParseAssignmentAnswer.pm »
| 1 | package Net::Amazon::MechanicalTurk::Properties; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use IO::File; | ||
| 5 | use Carp; | ||
| 6 | |||
| 7 | our $VERSION = '1.00'; | ||
| 8 | |||
| 9 | sub toProperties { | ||
| 10 | my ($class, $properties) = @_; | ||
| 11 | if (UNIVERSAL::isa($properties, "HASH")) { | ||
| 12 | return $properties; | ||
| 13 | } | ||
| 14 | else { | ||
| 15 | return Net::Amazon::MechanicalTurk::Properties->readNestedData($properties); | ||
| 16 | } | ||
| 17 | } | ||
| 18 | |||
| 19 | sub write { | ||
| 20 | my ($class, $settings, $file, $header) = @_; | ||
| 21 | my $out = IO::File->new($file, "w"); | ||
| 22 | if (!$out) { | ||
| 23 | Carp::croak("Could not open file $file - $!."); | ||
| 24 | } | ||
| 25 | if ($header) { | ||
| 26 | foreach my $line (split /\r?\n/, $header) { | ||
| 27 | printf $out "# %s\n", $line; | ||
| 28 | } | ||
| 29 | } | ||
| 30 | foreach my $key (sort keys %$settings) { | ||
| 31 | my $value = $settings->{$key}; | ||
| 32 | printf $out "%s: %s\n", $key, $value; | ||
| 33 | } | ||
| 34 | $out->close; | ||
| 35 | } | ||
| 36 | |||
| 37 | # Reads a properties file into a nested data structure | ||
| 38 | sub readNestedData { | ||
| 39 | my ($class, $in) = @_; | ||
| 40 | return Net::Amazon::MechanicalTurk::DataStructure->fromProperties($class->read($in)); | ||
| 41 | } | ||
| 42 | |||
| 43 | # Reads a file into key value pairs and returns a hash. | ||
| 44 | # The file should be similar to that of a Java properties file. | ||
| 45 | # Backslash escaping is not supported though. | ||
| 46 | # Both = and : can be used as key/value separators. | ||
| 47 | sub read { | ||
| 48 | my ($class, $in) = @_; | ||
| 49 | my $file = "<stream>"; | ||
| 50 | |||
| 51 | if (!UNIVERSAL::isa($in, "GLOB")) { | ||
| 52 | $file = $in; | ||
| 53 | $in = IO::File->new($file, "r"); | ||
| 54 | if (!$in) { | ||
| 55 | Carp::croak("Could not read file $file - $!."); | ||
| 56 | } | ||
| 57 | } | ||
| 58 | |||
| 59 | my $props = {}; | ||
| 60 | my $lineno = 0; | ||
| 61 | while (my $line = <$in>) { | ||
| 62 | next if ($line =~ /^\s*[#!]/ or $line =~ /^\s*$/); | ||
| 63 | if ($line =~ /^([^:=]+)[=:](.*)/) { | ||
| 64 | my ($key,$val) = ($1,$2); | ||
| 65 | $key =~ s/^\s+//; | ||
| 66 | $key =~ s/\s+$//; | ||
| 67 | $val =~ s/^\s+//; | ||
| 68 | $val =~ s/\s+$//; | ||
| 69 | $props->{$key} = $val; | ||
| 70 | } | ||
| 71 | else { | ||
| 72 | warn "Unknown format at $file:$lineno."; | ||
| 73 | } | ||
| 74 | } | ||
| 75 | |||
| 76 | return $props; | ||
| 77 | } | ||
| 78 | |||
| 79 | return 1; |