문제

최근까지, 나는 여러 값을 다음과 같은 키로 다른 해시에 저장하고 있습니다.

%boss = (
    "Allan"  => "George",
    "Bob"    => "George",
    "George" => "lisa" );

%status = (
    "Allan"  => "Contractor",
    "Bob"    => "Part-time",
    "George" => "Full-time" );

그런 다음 참조 할 수 있습니다 $boss("Bob") 그리고 $status("Bob") 그러나 각 키가 가질 수있는 속성이 많고 해시를 동기화하는 것에 대해 걱정해야합니다.

해시에 여러 값을 저장하는 더 좋은 방법이 있습니까? 값을 다음과 같이 저장할 수 있습니다

        "Bob" => "George:Part-time"

그런 다음 스플릿으로 문자열을 분해하지만 더 우아한 방법이 있어야합니다.

도움이 되었습니까?

해결책

이것은 표준 방식입니다 perldoc perldsc.

~> more test.pl
%chums = ( "Allan" => {"Boss" => "George", "Status" => "Contractor"},
           "Bob" => {"Boss" => "Peter", "Status" => "Part-time"} );

print $chums{"Allan"}{"Boss"}."\n";
print $chums{"Bob"}{"Boss"}."\n";
print $chums{"Bob"}{"Status"}."\n";
$chums{"Bob"}{"Wife"} = "Pam";
print $chums{"Bob"}{"Wife"}."\n";

~> perl test.pl
George
Peter
Part-time
Pam

다른 팁

해시 해시는 당신이 명시 적으로 요구하는 것입니다. Perl 문서의 튜토리얼 스타일 문서 부분이 있습니다. 데이터 구조 요리 책 그러나 아마도 당신은 객체 지향을 고려해야 할 것입니다. 이것은 객체 지향 프로그래밍 튜토리얼의 일종의 전형적인 예입니다.

이와 같은 것은 어떻습니까 :

#!/usr/bin/perl
package Employee;
use Moose;
has 'name' => ( is => 'rw', isa => 'Str' );

# should really use a Status class
has 'status' => ( is => 'rw', isa => 'Str' );

has 'superior' => (
  is      => 'rw',
  isa     => 'Employee',
  default => undef,
);

###############
package main;
use strict;
use warnings;

my %employees; # maybe use a class for this, too

$employees{George} = Employee->new(
  name   => 'George',
  status => 'Boss',
);

$employees{Allan} = Employee->new(
  name     => 'Allan',
  status   => 'Contractor',
  superior => $employees{George},
);

print $employees{Allan}->superior->name, "\n";

해시에는 다른 해시 또는 배열이 포함될 수 있습니다. 속성을 이름으로 언급하려면 키 당 해시로 저장하고, 그렇지 않으면 키당 배열로 저장하십시오.

이있다 구문에 대한 참조.

my %employees = (
    "Allan" => { "Boss" => "George", "Status" => "Contractor" },
);

print $employees{"Allan"}{"Boss"}, "\n";

%chums = ( "allan"=> { "boss"=> "george", "status"=> "contractor"}, "bob"=> { "boss"=> "peter", "status"=> " 파트 타임 "});

훌륭하게 작동하지만 데이터를 입력하는 더 빠른 방법이 있습니까?

나는 같은 것을 생각하고있다

여기서 x = 기본 키 이후 보조 키 수,이 경우 x = 2, "보스"및 "상태"

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top