use constant SEARCH_TERM => "some_search_term"; parse_from_twitter_stream(); sub parse_from_twitter_stream { my $user = 'XXXXX'; my $password = 'YYYYY'; my $stream = Net::Twitter::Stream->new ( user => $user, pass => $password, callback => \&got_tweet, connection_closed_cb => \&connection_closed, track => SEARCH_TERM); sub connection_closed { sleep 1; warn "Connection to Twitter closed"; parse_from_twitter_stream(); } sub got_tweet { my ( $tweet, $json ) = @_; # a hash containing the tweet # and the original json warn "Got tweet"; #I have more code here but it's snipped } } #### sub new { my $class = shift; my %args = @_; die "Usage: Net::Twitter::Stream->new ( user => 'user', pass => 'pass', callback => \&got_tweet_cb )" unless $args{user} && $args{pass} && $args{callback}; my $self = bless {}; $self->{user} = $args{user}; $self->{pass} = $args{pass}; $self->{got_tweet} = $args{callback}; $self->{connection_closed} = $args{connection_closed_cb} if $args{connection_closed_cb}; my $content = "follow=$args{follow}" if $args{follow}; $content = "track=$args{track}" if $args{track}; $content = "follow=$args{follow}&track=$args{track}\r\n" if $args{track} && $args{follow}; my $auth = encode_base64 ( "$args{user}:$args{pass}" ); chomp $auth; my $cl = length $content; my $req = <new ( PeerAddr => 'stream.twitter.com:https' ); $sock->print ( "$req$content" ); while ( my $l = $sock->getline ) { last if $l =~ /^\s*$/; } while ( my $l = $sock->getline ) { next if $l =~ /^\s*$/; # skip empty lines $l =~ s/[^a-fA-F0-9]//g; # stop hex from compaining about \r my $jsonlen = hex ( $l ); last if $jsonlen == 0; eval { my $json; my $len = $sock->read ( $json, $jsonlen ); my $o = from_json ( $json ); $self->{got_tweet} ( $o, $json ); }; } $self->{connection_closed} ( $sock ) if $self->{connection_closed}; }