2015-11-16 89 views
0

這裏是我的代碼:如何計算一個對象內數組的長度?

#!/usr/bin/perl 

use Net::Twitter; 
use JSON; 
use LWP::Simple; 
use XML::Bare; 
use Data::Dumper; 

# keys for twitter 
$consumer_key = "key"; 
$consumer_secret = "key"; 
$token = "key-key"; 
$token_secret = "key"; 

# As of 13-Aug-2010, Twitter requires OAuth for authenticated requests 
my $nt = Net::Twitter->new(
    traits => [qw/API::RESTv1_1/], 
    # traits => [qw/API::Search/], 
    consumer_key  => $consumer_key, 
    consumer_secret  => $consumer_secret, 
    access_token  => $token, 
    access_token_secret => $token_secret, 
); 

$UserID = 46562311; 


my $IDs = $nt->friends_ids({user_id => $UserID}); 
print Dumper $IDs->{ids}; 

輸出是:

$ VAR1 = [ 1243478918, 472407213, 1152523333, 18080969, 36843988, 24467012, 322990625, 15492359, 2244340904, 22938914, 151180133, 58545637, 62513246, 28412286, 5746452, 17104751, 1636590253, 25073877, 8161232, 2384071, 13, 93957809, 22330739, 44196397, 132961448, 754500, 94384796, 59604041, 386854967, 15485441, 190617492, 226237599, 114485232, 190486752, 18645153, 326350862, 546915948, 1927794380, 244360712, 254674228, 43593, 17242168, 17268874, 117539435, 116737145, 326642243, 1010165784, 19583340, 7936522, 166739404, 50374439, 593893034 , 1244526223, 783214, 382267114, 299743215, 16129880, 20536157, 17006157, 2249234689, 26761757, 17919972, 2244994945, 1526228120, 11348282, 14159148, 50393960, 1339835893, 409685881, 2469260288, 1012494116, 270816968, 813286, 2546660556, 518542127 , 794611698, 108962082, 1626691956, 734314441, 20351217, 1692371666, 774980724, 865699670, 1958038938, 826539409, 805891104, 14749606, 391858548,];

如何計算此數組的長度?我用「長度$ ID - > {ids}」,但它只給了我21,這顯然是錯誤的。

回答

4

可以使用scalar內建函數:

print scalar @{ $IDs->{ids} }; 

它迫使它在標量上下文來解釋的說法。正如你所知的標量上下文中的數組被評估爲它的長度。

+0

謝謝,但「print scalar @ {$ IDs - > {ids}};」結果給我「1」。奇怪的。 –

+0

@NoahSong:我得到89.它返回1,但打印89. – choroba

+0

@choroba哦,謝謝!看來我剛剛達到了費率限制.. –