Search code examples
arraysperldatereferencedereference

Match Array to a Value within an Array of References - Perl


I have the following array of references to arrays:

my @holidays = [[2012,'01','02'],[2012,'01','16'],[2012,'02','20'],[2012,'04','16'],[2012,'05','28'],[2012,'07','04'],[2012,'09','03'],[2012,'10','08'],[2012,'11','12'],[2012,'11','22'],[2012,'12','25']];

Which are IRS recognized legal holidays during 2012. I would like to match the array @dueDate to a value in that array and return 1 or true if it is present.

    while ($holidays[@dueDate]){
        print ("Found Holiday \t join('-',@dueDate)");
        @dueDate = Add_Delta_Days(@dueDate, 1);
        if ( Day_of_Week(@dueDate) > 5){
            @dueDate = Monday_of_Week((Week_Number(@dueDate)+1), $dueDate[0]);
        }
    }

Is my current attempt at this - the condition of the while statement is never true. I've tried a few different combinations of referencing and dereferencing holidays to no avail.

What would the best way be to manipulate the evaluation within the while statement such that the block executes when @dueDate contains a date within my array above.

Note: @dueDate is a Date::Calc standard array - (Year, Month, Day)


Solution

  • This should put you on the right track. Two problems I see with your code - an array of arrays should have normal parentheses on the outer part, and use the ~~ operator to compare arrays for equality.

    my @holidays = ([2012,'01','02'],[2012,'01','16'],[2012,'02','20'],[2012,'04','16'],  
    [2012,'05','28'],[2012,'07','04'],[2012,'09','03'],[2012,'10','08'],[2012,'11','12'], 
    [2012,'11','22'],[2012,'12','25']);
    my $i;
    my @duedate = [2012, '01', '02'];
    
    for ($i = 0; $i < @holidays; $i++)
    {
        if (@holidays[$i] ~~ @duedate)
        {
            print "matched!!";
        }
    }